我需要从字符串的末尾删除空格。我该怎么做呢? 示例:如果字符串是“Hello”,它必须变成“Hello”
当前回答
从这里的答案来看: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:@""];
}
在Swift中删除字符串开头和结尾的空格:
斯威夫特3
string.trimmingCharacters(in: .whitespacesAndNewlines)
Swift以前的版本
string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))
这将只删除您选择的尾随字符。
func trimRight(theString: String, charSet: NSCharacterSet) -> String {
var newString = theString
while String(newString.characters.last).rangeOfCharacterFromSet(charSet) != nil {
newString = String(newString.characters.dropLast())
}
return newString
}
从这里的答案来看: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
}
let string = "测试修剪过的字符串"
对于删除空白和新行使用以下代码:-
let str_trim = yourString。trimmingCharacters (.whitespacesAndNewlines):
对于仅从字符串中删除空格使用以下代码:-
let str_trim = yourString。trimmingCharacters (.whitespaces):