Friday, May 20, 2011

NSString componentsSeparatedByCharactersInSet example objc

componentsSeparatedByCharactersInSet:

Returns an array containing substrings from the receiver that have been divided by characters in a given set.
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
Parameters
separator
A character set containing the characters to to use to split the receiver. Must not be nil.
Return Value
An NSArray object containing substrings from the receiver that have been divided by characters in separator.
Discussion of componentsSeparatedByCharactersInSet
The substrings in the array appear in the order they did in the receiver. Adjacent occurrences of the separator characters produce empty strings in the result. Similarly, if the string begins or ends with separator characters, the first or last substring, respectively, is empty.

Example of [NSString componentsSeparatedByCharactersInSet

The method returns an array containing substrings from the receiver that have been divided by characters in a given set. [NSString componentsSeparatedByCharactersInSet] performs very simple lexical analysis internally to separate the string. See following code for real usage. 

NSString *str = @"A~B^C";
NSArray *arr = [str componentsSeparatedByCharactersInSet:
          [NSCharacterSet characterSetWithCharactersInString:@"^~"]];
NSLog(@"%@", arr);