Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if NSString begins with a certain character

People also ask

How do I find the first character of a string in Objective C?

You want: NSString *firstLetter = [codeString substringToIndex:1];

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+

Do I need to release NSString?

If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.


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


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
}

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