Trim spaces from end of a NSString

前端 未结 14 1171
既然无缘
既然无缘 2020-11-27 09:26

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\"

14条回答
  •  借酒劲吻你
    2020-11-27 09:49

    The solution is described here: How to remove whitespace from right end of NSString?

    Add the following categories to NSString:

    - (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
    }
    
    - (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
        return [self stringByTrimmingTrailingCharactersInSet:
                [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    }
    

    And you use it as such:

    [yourNSString stringByTrimmingTrailingWhitespaceAndNewlineCharacters]
    

提交回复
热议问题