我需要从字符串的末尾删除空格。我该怎么做呢? 示例:如果字符串是“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
}
另一个解决方案涉及创建可变字符串:
//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的结尾将没有空格。
我想出了这个函数,它的行为基本类似于Alex的答案:
-(NSString*)trimLastSpace:(NSString*)str{
int i = str.length - 1;
for (; i >= 0 && [str characterAtIndex:i] == ' '; i--);
return [str substringToIndex:i + 1];
}
whitespaceCharacterSet除了空格本身还包括制表符,在我的情况下不能出现。所以我想一个简单的比较就足够了。
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//for remove whitespace and new line character
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet punctuationCharacterSet]];
//for remove characters in punctuation category
还有许多其他字符集。根据你的要求自己检查一下。
NSString* NSStringWithoutSpace(NSString* string)
{
return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}
斯威夫特版本
只修整字符串末尾的空格:
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())
在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
}
在斯威夫特
从字符串的两侧修剪空格和换行:
var url: String = "\n http://example.com/xyz.mp4 "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.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的右端删除空白?
添加以下类别到NSString:
- (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 *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
return [self stringByTrimmingTrailingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
你可以这样使用它:
[yourNSString stringByTrimmingTrailingWhitespaceAndNewlineCharacters]
要修剪所有尾随的空格字符(我猜这实际上是你的意图),下面是一种相当干净简洁的方法。
斯威夫特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)];
一行,加上一段正则表达式。
let string = "测试修剪过的字符串"
对于删除空白和新行使用以下代码:-
let str_trim = yourString。trimmingCharacters (.whitespacesAndNewlines):
对于仅从字符串中删除空格使用以下代码:-
let str_trim = yourString。trimmingCharacters (.whitespaces):