Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if an NSString starts with a certain other string?

People also ask

How do I check if a string contains another string in Objective C?

To check if a string contains another string in objective-c, we can use the rangeOfString: instance method where it returns the {NSNotFound, 0} if a 'searchString' is not found or empty (""). Output: string contains you!

How to check if string is empty in objective c?

You can check if [string length] == 0 . This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

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.

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.


Try this: if ([myString hasPrefix:@"http"]).

By the way, your test should be != NSNotFound instead of == NSNotFound. But say your URL is ftp://my_http_host.com/thing, it'll match but shouldn't.


I like to use this method:

if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}

or even easier:

if ([temp hasPrefix:@"http"]) {
    //do your stuff
}

If you're checking for "http:" you'll probably want case-insensitive search:

NSRange prefixRange = 
    [temp rangeOfString:@"http" 
                options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
if (prefixRange.location == NSNotFound)

Swift version:

if line.hasPrefix("#") {
  // checks to see if a string (line) begins with the character "#"
}