Split an NSString to access one particular piece

cyclingIsBetter picture cyclingIsBetter · Apr 27, 2011 · Viewed 139.9k times · Source

I have a string like this: @"10/04/2011" and I want to save only the "10" in another string. How can I do that?

Answer

JeremyP picture JeremyP · Apr 27, 2011
NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* firstBit = [foo objectAtIndex: 0];

Update 7/3/2018:

Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:

let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]

Although note that it gives you an array of Substring. If you need to convert these back to ordinary strings, use map

let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]

or

let firstBit = String(substrings[0])