23

我有一个NSString,这有多个空格,我想修剪这些空格并为例如@“how.....are.......you”创建一个空格到@“how are you”。(点只是空格)

我试过了

NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceCharacterSet]];

它似乎不起作用。任何的想法。

4

8 回答 8

47

您可以使用正则表达式来完成此操作:

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:@" "];
于 2012-08-27T06:27:55.290 回答
12

这在我尝试时有效:

NSString *trimmedString = @"THIS      IS      A     TEST S    STRING   S D        D F ";
    while ([trimmedString rangeOfString:@"  "].location != NSNotFound) {
        trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"  " withString:@" "];
    }
NSLog(@"%@", trimmedString);
于 2012-08-27T07:02:18.463 回答
11

用户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:@" "];
于 2012-08-27T06:24:41.533 回答
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: " ")
于 2017-04-10T09:55:25.570 回答
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:@" "];
于 2014-06-13T10:18:07.710 回答
0

斯威夫特 4:

let stringOut = stringIn.replacingOccurrences(of: " +", with: " ", options: String.CompareOptions.regularExpression, range: nil)
于 2018-08-24T10:18:59.320 回答
-1
NSString* NSStringWithoutSpace(NSString* string)
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}
于 2014-09-02T07:34:36.197 回答
-3

您可以使用:

NSString *trimmedString = [user_ids stringByReplacingOccurrencesOfString: @" " withString:@""];
于 2012-08-27T06:16:07.343 回答