Jeffrey Kern
Jeffrey Kern

Reputation: 2024

Objective C: String tokenization

Is there a good way to tokenize the following string? I'd like to get the letters between the brackets.

The [quick] brown fox leaped [onto] the [heli][copter].

The easiest solution I've thought of, was to tokenize the initial string into an array with [. I'd then iterate the array and tokenize each item with ], returning the first item. To improve efficiency, I'd check each string to make sure it contains the token in question before doing more involved processing.

However, this seems hackish and amateur. Plus, the example above would create 5 arrays to process the string. Anyone have ideas?

Upvotes: 0

Views: 145

Answers (1)

Blaluma
Blaluma

Reputation: 26

An option would be to use regular expressions to search your string for the wanted values:

NSString *myString = @"The [quick] brown fox leaped [onto] the [heli][copter].";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression         
    regularExpressionWithPattern:@"\\[.*?\\]"
    options:NSRegularExpressionCaseInsensitive
    error:&error];
[regex enumerateMatchesInString:myString options:0 range:NSMakeRange(0, [myString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
    //Handle your matches here
}];

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/

In this case the values returned would still include the brackets. If you only want the values you can remove the brackets for each value like:

string = [string substringFromIndex:1];

and

string = [string substringToIndex:[string length] - 1];

RegEx can be created/validated e.g.: http://www.regexr.com

/edit: changed RegEx to the one proposed in the comments by Nikolai Ruhe. Thanks.

Upvotes: 1

Related Questions