How to check if NSString begins with a certain character

Xetius picture Xetius · Mar 23, 2010 · Viewed 109k times · Source

How do you check if an NSString begins with a certain character (the character *).

The * is an indicator for the type of the cell, so I need the contents of this NSString without the *, but need to know if the * exists.

Answer

Rob Keniger picture Rob Keniger · Mar 23, 2010

You can use the -hasPrefix: method of NSString:

Objective-C:

NSString* output = nil;
if([string hasPrefix:@"*"]) {
    output = [string substringFromIndex:1];
}

Swift:

var output:String?
if string.hasPrefix("*") {
    output = string.substringFromIndex(string.startIndex.advancedBy(1))
}