Trim spaces from end of a NSString

前端 未结 14 1149
既然无缘
既然无缘 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:56

    Here you go...

    - (NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
        NSUInteger location = 0;
        unichar charBuffer[[strtoremove length]];
        [strtoremove getCharacters:charBuffer];
        int i = 0;
        for(i = [strtoremove length]; i >0; i--) {
            NSCharacterSet* charSet = [NSCharacterSet whitespaceCharacterSet];
            if(![charSet characterIsMember:charBuffer[i - 1]]) {
                break;
            }
        }
        return [strtoremove substringWithRange:NSMakeRange(location, i  - location)];
    }
    

    So now just call it. Supposing you have a string that has spaces on the front and spaces on the end and you just want to remove the spaces on the end, you can call it like this:

    NSString *oneTwoThree = @"  TestString   ";
    NSString *resultString;
    resultString = [self removeEndSpaceFrom:oneTwoThree];
    

    resultString will then have no spaces at the end.

提交回复
热议问题