Trim spaces from end of a NSString

Andrea Mario Lufino picture Andrea Mario Lufino · Apr 22, 2011 · Viewed 174.8k times · Source

I need to remove spaces from the end of a string. How can I do that? Example: if string is "Hello " it must become "Hello"

Answer

Dan picture Dan · Apr 22, 2011

Taken from this answer here: https://stackoverflow.com/a/5691567/251012

- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
    NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
                                                               options:NSBackwardsSearch];
    if (rangeOfLastWantedCharacter.location == NSNotFound) {
        return @"";
    }
    return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}