views:

399

answers:

3

Hi,

Does anyone know a nice efficient way of finding a string within a string (if it exists) in objective c for iPhone Development, I need to find the part of the string in between two words, e.g. here I need to find the co2 rating number in the string, where z is the value I'm looking for ...

xxxxxco_2zendxxxxxxx

Thanks

Richard www.creativetechnologist.co.uk

+2  A: 

This might be of interest to you (in particular the rangeOfString function):

(NSRange)rangeOfString:(NSString *)aString

Unfortunately Cocoa doesn't have any built-in RegEx support..

Miky Dinescu
A: 

String matching is a well explored domain especially for algorithms dealing with genetic material. You could check out the Art of Computer programming for 10x more than you ever wanted to know about string matching.

Most of that is overkill and you would be fine using a regular expression. Check out http://regexkit.sourceforge.net/RegexKitLite/ a regex library which runs on the iphone.

stimms
Cheers, didn't know that was available.
Richard Smith
+5  A: 

Ideally, I'd use a regular expression for this, probably something like co_2(.*?)end, so I'd take a look at RegexKitLite as stimms suggests.

If that is not suitable, you could extract the string you're looking for with something like this:

NSString* src = @"xxxxxco_2zendxxxxxxx";
NSRange startMarker = [src rangeOfString:@"co_2"];

if (startMarker.location != NSNotFound) {
    NSScanner* scanner = [NSScanner scannerWithString:src];
    [scanner setScanLocation:startMarker.location + startMarker.length];
    NSString* co2Value = @"";
    [scanner scanUpToString:@"end" intoString:&co2Value];
    NSLog(@"co_2 value is %@", co2Value);
} else {
    NSLog(@"co_2 marker not found");
}

Here we look for @"co_2", failing if it's not found, then use an NSScanner to grab everything from just after that string to the next occurrence of @"end". Note that if @"end" is missing this code will silently grab the rest of the string.

Will Harris
Perfect, thanks. Code worked first time too!
Richard Smith