Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get substring of NSString?

If I want to get a value from the NSString @"value:hello World:value", what should I use?

The return value I want is @"hello World".

like image 252
Csabi Avatar asked Apr 15 '11 11:04

Csabi


2 Answers

Option 1:

NSString *haystack = @"value:hello World:value"; NSString *haystackPrefix = @"value:"; NSString *haystackSuffix = @":value"; NSRange needleRange = NSMakeRange(haystackPrefix.length,                                   haystack.length - haystackPrefix.length - haystackSuffix.length); NSString *needle = [haystack substringWithRange:needleRange]; NSLog(@"needle: %@", needle); // -> "hello World" 

Option 2:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^value:(.+?):value$" options:0 error:nil]; NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)]; NSRange needleRange = [match rangeAtIndex: 1]; NSString *needle = [haystack substringWithRange:needleRange]; 

This one might be a bit over the top for your rather trivial case though.

Option 3:

NSString *needle = [haystack componentsSeparatedByString:@":"][1]; 

This one creates three temporary strings and an array while splitting.


All snippets assume that what's searched for is actually contained in the string.

like image 200
Regexident Avatar answered Sep 22 '22 08:09

Regexident


Here's a slightly less complicated answer:

NSString *myString = @"abcdefg"; NSString *mySmallerString = [myString substringToIndex:4]; 

See also substringWithRange and substringFromIndex

like image 31
Shaun Neal Avatar answered Sep 19 '22 08:09

Shaun Neal