我需要从字符串的末尾删除空格。我该怎么做呢? 示例:如果字符串是“Hello”,它必须变成“Hello”
当前回答
要修剪所有尾随的空格字符(我猜这实际上是你的意图),下面是一种相当干净简洁的方法。
斯威夫特5:
let trimmedString = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
objective - c:
NSString *trimmedString = [string stringByReplacingOccurrencesOfString:@"\\s+$" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
一行,加上一段正则表达式。
其他回答
从这里的答案来看: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
}
另一个解决方案涉及创建可变字符串:
//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"
在Swift中删除字符串开头和结尾的空格:
斯威夫特3
string.trimmingCharacters(in: .whitespacesAndNewlines)
Swift以前的版本
string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))
在Objective-C中只修剪一端而不是两端的简单解决方案:
@implementation NSString (category)
/// trims the characters at the end
- (NSString *)stringByTrimmingSuffixCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger i = self.length;
while (i > 0 && [characterSet characterIsMember:[self characterAtIndex:i - 1]]) {
i--;
}
return [self substringToIndex:i];
}
@end
和一个对称的实用工具,仅用于修剪开头:
@implementation NSString (category)
/// trims the characters at the beginning
- (NSString *)stringByTrimmingPrefixCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger i = 0;
while (i < self.length && [characterSet characterIsMember:[self characterAtIndex:i]]) {
i++;
}
return [self substringFromIndex:i];
}
@end
NSString* NSStringWithoutSpace(NSString* string)
{
return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}