小编典典

从 NSString 的末尾修剪空格

all

我需要从字符串末尾删除空格。我怎样才能做到这一点?示例:如果字符串是"Hello "它必须成为"Hello"


阅读 81

收藏
2022-03-28

共1个答案

小编典典

取自这里的答案:

- (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
}
2022-03-28