Search code examples
nsmutablearraynsarray

I have an NSArray of NSStrings which I need to iterate, and remove all of the underscores in each NSString


I have an application where I have an NSArray of NSStrings. The problem is that these NSStrings all have "_" between each word which I need to remove. Unfortunately I am not sure how to do this.

This is the code I am working with:

for (NSString *word in wordList) {

        [word stringByReplacingOccurrencesOfString:@"_" withString:@" "];
        [wordTypeList addObject:word];

    }

where wordTypeList is an NSMutableArray. My output unfortunately is the contents of the array, with no change (i.e. underscores have not been removed). What is it that I'm doing wrong?


Solution

  • stringByReplacingOccurrencesOfString returns a new NSString *, it does not modify the existing one.

    Change your code to the following:

    for (NSString *word in wordList) {
    
        NSString * newWord = [word stringByReplacingOccurrencesOfString:@"_" withString:@" "];
        [wordTypeList addObject:newWord];
    
    }