-2

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!

Josh
  • 12,448
  • 10
  • 74
  • 118
  • 4
    What have you tried? It doesn't seem like anything, since you're not even writing Objective-C but just some pseudo-language. Apple Developer docs are a great resource, please use them. – Joost Dec 01 '10 at 21:18
  • Honestly I haven't tried anything, I just got a bug report on one my iPhone apps, and having a bit longer at work, I was hoping I'd get a quick snippet so when I run home I can submit a patch to apple asap. – Josh Dec 01 '10 at 21:22

4 Answers4

7

The best way to split a NSString is:

- (NSArray *)componentsSeparatedByString:(NSString *)separator;

I hope you found it usefull

Oriol Blanc
  • 151
  • 2
  • 4
2
- (NSString *)splitString {
    NSRange range = [myString rangeOfString:@"RESULT: "];
    if (range.location != NSNotFound) {
        return [myString substringFromIndex:NSMaxRange(range)];
    }
    return nil;
}

Edited to return suffix, not prefix

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
2

Alright then, two quick methods:

-[NSString hasPrefix:]
-[NSString substringFromIndex:]

However don't forget to handle invalid cases.

Joost
  • 10,333
  • 4
  • 55
  • 61
1

For even greater flexibility, you could try NSScanners.

Richard
  • 3,316
  • 30
  • 41