我需要从字符串的末尾删除空格。我该怎么做呢? 示例:如果字符串是“Hello”,它必须变成“Hello”


当前回答

斯威夫特版本

只修整字符串末尾的空格:

private func removingSpacesAtTheEndOfAString(var str: String) -> String {
    var i: Int = countElements(str) - 1, j: Int = i

    while(i >= 0 && str[advance(str.startIndex, i)] == " ") {
        --i
    }

    return str.substringWithRange(Range<String.Index>(start: str.startIndex, end: advance(str.endIndex, -(j - i))))
}

修整字符串两侧的空格:

var str: String = " Yolo "
var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

其他回答

从这里的答案来看: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
}
NSString* NSStringWithoutSpace(NSString* string)
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}

另一个解决方案涉及创建可变字符串:

//make mutable string
NSMutableString *stringToTrim = [@" i needz trim " mutableCopy];

//pass it by reference to CFStringTrimSpace
CFStringTrimWhiteSpace((__bridge CFMutableStringRef) stringToTrim);

//stringToTrim is now "i needz trim"

给你…

- (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)];
}

现在就叫它。假设你有一个字符串,它前面有空格,后面也有空格,你只想去掉末尾的空格,你可以这样调用它:

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

resultString的结尾将没有空格。

斯威夫特版本

只修整字符串末尾的空格:

private func removingSpacesAtTheEndOfAString(var str: String) -> String {
    var i: Int = countElements(str) - 1, j: Int = i

    while(i >= 0 && str[advance(str.startIndex, i)] == " ") {
        --i
    }

    return str.substringWithRange(Range<String.Index>(start: str.startIndex, end: advance(str.endIndex, -(j - i))))
}

修整字符串两侧的空格:

var str: String = " Yolo "
var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())