Split an NSString
-
29-09-2019 - |
Question
Quick question. I need to split an NSString, if it contains a certain substring. Can someone show me an example of how to do this?
// good string
string = RESULT: 123.23
// bad string (has no result prefix)
string = asldkfjasdlkfj
if( string has "RESULT: " in it )
{
string2 = (something that returns the 123.23 part)
}
Thanks very much!
Solution
Alright then, two quick methods:
-[NSString hasPrefix:]
-[NSString substringFromIndex:]
However don't forget to handle invalid cases.
OTHER TIPS
The best way to split a NSString is:
- (NSArray *)componentsSeparatedByString:(NSString *)separator;
I hope you found it usefull
- (NSString *)splitString {
NSRange range = [myString rangeOfString:@"RESULT: "];
if (range.location != NSNotFound) {
return [myString substringFromIndex:NSMaxRange(range)];
}
return nil;
}
Edited to return suffix, not prefix
For even greater flexibility, you could try NSScanners.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow