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 [NSString 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]
NSString *str = @"A~B^C";
NSArray *arr = [str componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@"^~"]];
NSLog(@"%@", arr);
Example of [NSString componentsSeparatedByCharactersInSet]
// characters we are going to split at
NSString *sep = @" -()";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
NSArray *strings = [joinedString componentsSeparatedByCharactersInSet:set];
// This is the simple way provided that the strings doesn't have spaces in them.
Example of [NSString componentsSeparatedByCharactersInSet]
@interface NSString (AlwaysReturnSomething)
- (NSArray *) alwaysReturnSomethingForComponentsSeparatedByCharactersInSet: (NSCharacterSet *) characterSet;
@end
@implementation NSString (AlwaysReturnSomething)
- (NSArray *) alwaysReturnSomethingForComponentsSeparatedByCharactersInSet: (NSCharacterSet *) characterSet
{
NSArray * arrayToReturn = [self componentsSeparatedByCharactersInSet: characterSet];
if(arrayToReturn == NULL) || ([arrayToReturn count] == 0)
{
arrayToReturn = [NSArray arrayWithObject: self];
}
return(arrayToReturn);
}
@end