skip to Main Content

I know how to remove first character from a word in swift like this:

var data = "CITY Singapore"
data.removeFirst()
print(data)//ITY Singapore

what i want is to remove the first word and space so the result is "Singapore".
How can i remove the first word and leading space in swift?

4

Answers


  1. You can try

    let data = "CITY Singapore"
    let res = data.components(separatedBy: " ").dropFirst().joined(separator: " ") 
    print(res)
    

    Or

    let res = data[data.range(of: " ")!.upperBound...] // may crash for no " " inside the string
    
    Login or Signup to reply.
  2. Or you can go with this too

    let strData = "CITY Singapore"
    
    if let data = strData.components(separatedBy: " ").dropFirst().first {
        // do with data
    }
    else {
        // fallback
    }
    
    Login or Signup to reply.
  3. This is a Regular Expression solution, the benefit is to modify the string in place.

    The pattern searches from the beginning of the string to the first space character

    var data = "CITY Singapore"
    if let range = data.range(of: "^\S+\s", options: .regularExpression) {
        data.removeSubrange(range)
    }
    
    Login or Signup to reply.
  4. You can use String’s enumerateSubstrings in range method (Foundation) using byWords option and remove the first enclosing range. You need also to stop enumeration after removing the range at the first occurrence:

    var string = "CITY Singapore"
    string.enumerateSubstrings(in: string.startIndex..., options: .byWords) { (_, _, enclosingRange, stop) in
        string.removeSubrange(enclosingRange)
        stop = true
    }
    string  // "Singapore"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search