Joon. P
Joon. P

Reputation: 2298

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

Upvotes: 2

Views: 1954

Answers (3)

Leo Dabus
Leo Dabus

Reputation: 236548

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

Upvotes: 9

Long Pham
Long Pham

Reputation: 7582

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

Upvotes: 0

ldiqual
ldiqual

Reputation: 15375

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.

Upvotes: 0

Related Questions