Objective C - NSRange and rangeOfString

520 views Asked by At

I have a little problem with NSRange and rangeOfString. I want to search a substring in a given string which is working fine, but only to find a exact string and theres the problem i need to find a substring which begins always the same and ends always the same. I tried it already with something like that:

    match = [strIn rangeOfString: @"truni/begin/*/end"];

But thats not working. So i need a way to to do this. Here is the specific part of the Code in full:

    NSRange match;
    match = [strIn rangeOfString: @"turni/begin/sHjeUUej/end"];
    NSRange range = NSMakeRange(match.location, match.length);
    NSString *strOut = [strIN substringWithRange:range];

You see the string "turni/begin/sHjeUUej/end" will always be the same except for the part "sHjeUUej". Hope someone can help me.

Thanks in advance.

3

There are 3 answers

1
zaph On

Use a regular expression with:

- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask

with an option of RegularExpressionSearch.

See ICU User Guide Regular Expressions for information on creating regular expressions.

1
Flexicoder On

you can use prefix/suffix

if ([strIn hasPrefix:@"truni/begin/"] && [strIn hasSuffix:@"end"]) {
   //match
0
joao.arruda On

You can use a simpler solution if you make sure that your string always starts with turni/begin/ and ends with /end.

You can use:

NSString *strOut = [[strIn stringByReplacingOccurrencesOfString:@"turni/begin/" withString:@""] stringByReplacingOccurrencesOfString:@"/end" withString:@""];

With that, you can retrieve the string between the two others with only one line of code and less comparations.