lavoy
lavoy

Reputation: 1926

Tokenize string on multiple characters in Objective-C

I am trying to build a string tokenizer that can tokenize on mutilple characters.

I know I can use:

[string componentsSeparatedByString:@"-"];

but I want to check for white space, dashes, and newlines.

How can this be done?

Upvotes: 1

Views: 1785

Answers (2)

jlehr
jlehr

Reputation: 15597

As Ahmed suggested, use NSCharacterSet to define the delimiter characters, as shown below:

NSString *s = @"foo\nbar baz-quux";

NSMutableCharacterSet *characterSet = [NSMutableCharacterSet whitespaceAndNewlineCharacterSet];
[characterSet addCharactersInString:@"-"];

NSArray *strings = [s componentsSeparatedByCharactersInSet:characterSet];

Upvotes: 1

Ahmed Masud
Ahmed Masud

Reputation: 22382

use:

  [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString: @"\n\t "]]

Upvotes: 4

Related Questions