1

我有字符串

“印第安诺波利斯大道,1000”

我需要得到“Avenida Indianopolis, 1000”

我怎样才能做到这一点?

4

4 回答 4

2

您可以使用正则表达式将所有包含两个或多个空格的内容替换为一个空格:

 {2,}

例子:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@" {2,}" options:0  error:NULL];

NSMutableString *string = [NSMutableString stringWithString:@"Avenida Indianopolis      , 1000"];
[regex replaceMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@" "];

但是,在您的示例中,这将导致逗号前有一个空格,因此您实际上可能希望用空替换空格(或对字符串运行第二遍并清理空格+逗号,具体取决于输入字符串的方式形成)

于 2013-01-08T12:44:15.530 回答
1

尝试

NSString *str = "Avenida Indianopolis &nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp, 1000";
str = [str stringByReplacingOccurrencesOfString:@"&nbsp" withString:@""]; 

如果存在空格而不是  ,请尝试此操作

NSString *str = "Avenida Indianopolis    , 1000";
str = [str stringByReplacingOccurrencesOfString:@"     " withString:@""]; 
于 2013-01-08T12:32:15.233 回答
0

尝试这个

NSString *string = @"Avenida Indianopolis &nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp, 1000";
string = [string stringByReplacingOccurrencesOfString:@"&nbsp" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@"&nbsp " withString:@""];

希望对你有帮助。。

编辑

NSString *string = @"Avenida Indianopolis &nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp, 1000";
string = [string stringByReplacingOccurrencesOfString:@"     " withString:@" "];
于 2013-01-08T12:33:16.553 回答
0

我认为关键是您需要删除“,”之前的所有空格。

为此,请使用正则表达式 @" +,":一个或多个空格,后跟一个逗号。

NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:@" +," options:0 error:NULL];

NSMutableString *data = [NSMutableString stringWithString:@"Avenida Indianopolis      , 1000"];
[re replaceMatchesInString:data options:0 range:NSMakeRange(0, data.length) withTemplate:@","];

STAssertEqualObjects(data, @"Avenida Indianopolis, 1000", nil);
于 2013-01-08T12:56:28.810 回答