Search code examples
nsstringwhitespacetrim

Trim spaces from end of a NSString


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"


Solution

  • 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
    }