215

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.

Xetius
  • 44,755
  • 24
  • 88
  • 123

10 Answers10

470

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))
}
Rob Keniger
  • 45,830
  • 6
  • 101
  • 134
  • Is there a way to use this same method, but instead of `hasPrefix:@"word"` you check for multiple values stored in an `NSArray`? For example: `NSArray *words = [NSArray arrayWithObjects:@"foo",@"bar",@"baz",nil];` ? – adamdehaven Aug 02 '13 at 14:27
  • ^^ See my question here: http://stackoverflow.com/questions/18019660/check-if-nsstring-hasprefix-that-is-contained-in-nsarray – adamdehaven Aug 02 '13 at 14:40
  • 1
    CFStringHasPrefix() can also be used on NSStrings due to "Toll Free Bridging". The performance of CFStringHasPrefix() seems to be 2-3 times better (at least when using my data set). So if you are using it in a performance sensitive area, you might want to try CFStringHasPrefix() instead. – John Bowers Feb 06 '14 at 21:00
12

You can use:

NSString *newString;
if ( [[myString characterAtIndex:0] isEqualToString:@"*"] ) {
     newString = [myString substringFromIndex:1];
}
Tyilo
  • 28,998
  • 40
  • 113
  • 198
Chris Long
  • 3,007
  • 4
  • 30
  • 37
8

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 for Return Value is YES if aString matches the beginning characters of the receiver, otherwise NO. Returns NO if aString is empty.

Manlio
  • 10,768
  • 9
  • 50
  • 79
Iggy
  • 8,463
  • 3
  • 31
  • 21
5

As a more general answer, try using the hasPrefix method. For example, the code below checks to see if a string begins with 10, which is the error code used to identify a certain problem.

NSString* myString = @"10:Username taken";

if([myString hasPrefix:@"10"]) {
      //display more elegant error message
}
Kyle Clegg
  • 38,547
  • 26
  • 130
  • 141
4

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

outis
  • 75,655
  • 22
  • 151
  • 221
4
NSString *stringWithoutAsterisk(NSString *string) {
    NSRange asterisk = [string rangeOfString:@"*"];
    return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}
Chuck
  • 234,037
  • 30
  • 302
  • 389
4

Another approach to do it..

May it help someone...

if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
1

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
  • 6,726
  • 4
  • 30
  • 44
0

This nice little bit of code I found by chance, and I have yet to see it suggested on Stack. It only works if the characters you want to remove or alter exist, which is convenient in many scenarios. If the character/s does not exist, it won't alter your NSString:

NSString = [yourString stringByReplacingOccurrencesOfString:@"YOUR CHARACTERS YOU WANT TO REMOVE" withString:@"CAN either be EMPTY or WITH TEXT REPLACEMENT"];

This is how I use it:

//declare what to look for
NSString * suffixTorRemove = @"</p>";
NSString * prefixToRemove = @"<p>";
NSString * randomCharacter = @"</strong>";
NSString * moreRandom = @"<strong>";
NSString * makeAndSign = @"&";

//I AM INSERTING A VALUE FROM A DATABASE AND HAVE ASSIGNED IT TO returnStr
returnStr = [returnStr stringByReplacingOccurrencesOfString:suffixTorRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:prefixToRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:randomCharacter withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:moreRandom withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:makeAndSign withString:@"&"];

//check the output
NSLog(@"returnStr IS NOW: %@", returnStr);

This one line is super easy to perform three actions in one:

  1. Checks your string for the character/s you do not want
  2. Can replaces them with whatever you like
  3. Does not affect surrounding code
App Dev Guy
  • 5,396
  • 4
  • 31
  • 54
0
NSString* expectedString = nil;
if([givenString hasPrefix:@"*"])
{
   expectedString = [givenString substringFromIndex:1];
}
iGatiTech
  • 2,306
  • 1
  • 21
  • 45
Vaibhav Shiledar
  • 939
  • 8
  • 15