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"
.
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.
Here's a slightly less complicated answer:
NSString *myString = @"abcdefg"; NSString *mySmallerString = [myString substringToIndex:4];
See also substringWithRange and substringFromIndex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With