2

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)] 

3 Answers 3

9

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") } 
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this crashes if ")" precedes "(" in the string, e.g. for text = "foo)bar(" .
0

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.

Comments

0

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)") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.