views:

757

answers:

5

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.

+1  A: 

Use characterAtIndex:. If the first character is an asterisk, use substringFromIndex: to get the string sans '*'.

outis
+3  A: 

You can use:

NSString *newString;
if ( [myString characterAtIndex:0] == '*' ) {
     newString = [myString substringFromIndex:1];
}
Chris Long
You can't send messages to unichars, and they probably won't be equal to NSStrings.
Chuck
Good point. Edited...
Chris Long
+1  A: 

This might help? :)

http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/characterAtIndex:

Just search for the character at index 0 and compare it against the value you're looking for!

djhworld
+3  A: 
NSString *stringWithoutAsterisk(NSString *string) {
    NSRange asterisk = [string rangeOfString:@"*"];
    return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}
Chuck
+7  A: 

You can use the -hasPrefix: method of NSString:

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