我有一个NSString
,它有多个空格,我想修剪这些空格并为@例如@“如何.....你......”制作一个单独的空格“你好吗”。(点只是空格)
我试过
NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
似乎不起作用。任何想法。
答案 0 :(得分:46)
您可以使用正则表达式来完成此任务:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@" +" options:NSRegularExpressionCaseInsensitive error:&error];
模式是一个空格,后跟一个或多个空格。将其替换为字符串中的单个空格:
NSString *trimmedString = [regex stringByReplacingMatchesInString:user_ids options:0 range:NSMakeRange(0, [user_ids length]) withTemplate:@" "];
答案 1 :(得分:11)
这在我尝试时起作用了:
NSString *trimmedString = @"THIS IS A TEST S STRING S D D F ";
while ([trimmedString rangeOfString:@" "].location != NSNotFound) {
trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@" " withString:@" "];
}
NSLog(@"%@", trimmedString);
答案 2 :(得分:10)
user1587011
NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
此字符串方法用于删除字符串开头和结尾的空格。
试试这个它可以提供你想要的东西: -
NSString *theString = @" Hello this is a long string! ";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:@" "];
答案 3 :(得分:1)
Swift 3 代码
let regex = try? NSRegularExpression(pattern: " +", options: .caseInsensitive)
let trimmedString: String? = regex?.stringByReplacingMatches(in: user_ids, options: [], range: NSRange(location: 0, length: user_ids.characters.count), withTemplate: " ")
答案 4 :(得分:0)
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\s{2,}+" options:NSRegularExpressionCaseInsensitive error:&error];
user_ids = [regex stringByReplacingMatchesInString:user_ids options:0 range:NSMakeRange(0, [s length]) withTemplate:@" "];
答案 5 :(得分:0)
迅速4:
let stringOut = stringIn.replacingOccurrences(of: " +", with: " ", options: String.CompareOptions.regularExpression, range: nil)
答案 6 :(得分:-1)
NSString* NSStringWithoutSpace(NSString* string)
{
return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}
答案 7 :(得分:-3)
你可以使用:
NSString *trimmedString = [user_ids stringByReplacingOccurrencesOfString: @" " withString:@""];