我有一个NSString,这有多个空格,我想修剪这些空格并为例如@“how.....are.......you”创建一个空格到@“how are you”。(点只是空格)
我试过了
NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
它似乎不起作用。任何的想法。
我有一个NSString,这有多个空格,我想修剪这些空格并为例如@“how.....are.......you”创建一个空格到@“how are you”。(点只是空格)
我试过了
NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
它似乎不起作用。任何的想法。
您可以使用正则表达式来完成此操作:
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:@" "];
这在我尝试时有效:
NSString *trimmedString = @"THIS IS A TEST S STRING S D D F ";
while ([trimmedString rangeOfString:@" "].location != NSNotFound) {
trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@" " withString:@" "];
}
NSLog(@"%@", trimmedString);
用户1587011
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:@" "];
所选答案的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: " ")
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\s{2,}+" options:NSRegularExpressionCaseInsensitive error:&error];
user_ids = [regex stringByReplacingMatchesInString:user_ids options:0 range:NSMakeRange(0, [s length]) withTemplate:@" "];
斯威夫特 4:
let stringOut = stringIn.replacingOccurrences(of: " +", with: " ", options: String.CompareOptions.regularExpression, range: nil)
NSString* NSStringWithoutSpace(NSString* string)
{
return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}
您可以使用:
NSString *trimmedString = [user_ids stringByReplacingOccurrencesOfString: @" " withString:@""];