需要对最后一个空格进行子串

时间:2013-01-08 12:29:14

标签: objective-c ios ios4 nsstring

我有字符串

"Avenida Indianopolis                , 1000"

我需要得到“Avenida Indianopolis,1000”

我该怎么做?

4 个答案:

答案 0 :(得分: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:@" "];

但是,在你的例子中,这会在逗号之前产生一个空格,所以你可能实际上想要用空格替换空格(或者在字符串上运行第二遍并清理空格+逗号,具体取决于你的方式输入字符串形成)

答案 1 :(得分:1)

尝试

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

如果存在空格而不是& nbsp

,请尝试此操作
NSString *str = "Avenida Indianopolis    , 1000";
str = [str stringByReplacingOccurrencesOfString:@"     " withString:@""]; 

答案 2 :(得分: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:@" "];

答案 3 :(得分: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);