How to check if NSString begins with a certain character How to check if NSString begins with a certain character objective-c objective-c

How to check if NSString begins with a certain character


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


You can use:

NSString *newString;if ( [[myString characterAtIndex:0] isEqualToString:@"*"] ) {     newString = [myString substringFromIndex:1];}


hasPrefix works especially well.for example if you were looking for a http url in a NSString, you would use componentsSeparatedByString to create an NSArray and the iterate the array using hasPrefix to find the elements that begin with http.

NSArray *allStringsArray =    [myStringThatHasHttpUrls componentsSeparatedByString:@" "]for (id myArrayElement in allStringsArray) {    NSString *theString = [myArrayElement description];    if ([theString hasPrefix:@"http"]) {        NSLog(@"The URL  is %@", [myArrayElement description]);    }}

hasPrefix returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.

- (BOOL)hasPrefix:(NSString *)aString, 

parameter aString is a string that you are looking forReturn Value is YES if aString matches the beginning characters of the receiver, otherwise NO. Returns NO if aString is empty.