Alex Rivera | Logout

Objective-C: How to extract part of a String (e.g. start with '#')

Asked 2011-07-26T05:52:19.323
32

I have a string as shown below,

NSString * aString = @"This is the #substring1 and #subString2 I want";

How can I select only the text starting with '#' (and ends with a space), in this case 'subString1' and 'subString2'?

Note: Question was edited for clarity

Edit
Report

1 Answer

11

Pretty simple, easy to understand version avoiding NSRange stuff:

NSArray * words = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
NSMutableArray * mutableWords = [NSMutableArray new];
for (NSString * word in words){
    if ([word length] > 1 && [word characterAtIndex:0] == '#'){
        NSString * editedWord = [word substringFromIndex:1];
        [mutableWords addObject:editedWord];
    }
}
answered 2012-10-27T06:40:47.040

Your Answer