简体   繁体   中英

How to substring using Swift? ios xcode

Substringing in swift feels so complicated

I want to get

abc

from

word(abc)

What is the easiest way of doing this?

And how can i fix the below code to work?

let str = "word(abc)"

// get index of (
let start = str.rangeOfString("(")

// get index of ) 
let end = str.rangeOfString(")")  

// substring between ( and )
let substring = str[advance(str.startIndex, start!.startIndex), advance(str.startIndex, end!.startIndex)] 

Xcode 8.2 • Swift 3.0.2

let text = "word(abc)"

// substring between ( and )
if let start = text.range(of: "("),
    let end  = text.range(of: ")", range: start.upperBound..<text.endIndex) {
    let substring = text[start.upperBound..<end.lowerBound]    // "abc"
} else {
    print("invalid input")
}

You can use stringByReplacingOccurrencesOfString :

var a = "word(abc)" // "word(abc)"
a = a.stringByReplacingOccurrencesOfString("word(", withString: "") // "abc)"
a = a.stringByReplacingOccurrencesOfString(")", withString: "") // "abc"

or the loop solution:

var a = "word(abc)"
for component in ["word(", ")"] {
    a = a.stringByReplacingOccurrencesOfString(component, withString: "")
}

For more complex stuff though, a regex would be neater.

Using regular expression.

let str = "ds)) ) ) (kj( (djsldksld (abc)"
var range: Range = str.rangeOfString("\\([a-zA-Z]*\\)", options:.RegularExpressionSearch)!
let subStr = str.substringWithRange(range).stringByReplacingOccurrencesOfString("\\(", withString: "", options: .RegularExpressionSearch).stringByReplacingOccurrencesOfString("\\)", withString: "", options: .RegularExpressionSearch)
println("subStr = \(subStr)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM