在 for 循环内部,我有一个 if 语句,如下所示:
if([numberValues rangeOfString:@"+"].location == NSNotFound) {
NSLog(@"Phone Number does not contain a plus sign.");
} else {
NSLog(@"Phone number does contain a +");
[numberValues stringByReplacingOccurrencesOfString:@"+" withString:@""];
NSLog(@"This new numberValues object should not have a + anymore: %@", numberValues);
}
我可以确认 rangeOfString:
方法调用完美运行,因为我的地址簿中有电话号码不以“+”开头,并且它会打印“电话号码不包含加号。”到日志。
我的问题是 stringByReplacingOccurrencesOfString:
调用不起作用。通话结束后,当我将 numberValues
对象数据打印到日志时,电话号码仍然看起来像这样“+13997573173”,而不是像“13997573173”这样没有加号的打印。
我什至尝试将方法调用中的“+”更改为电话号码的前 4 位数字,但它仍然不会用新字符串替换目标字符串。
它每次都打印相同的值。知道为什么 stringByReplacingOccurrencesOfString:
对我不起作用吗?
最佳答案
stringByReplacingOccurrencesOfString:withString:
方法实际上返回一个字符串,并且不会改变您传入的字符串。
所以你可能想做这样的事情:
numberValues = [numberValues stringByReplacingOccurrencesOfString:@"+"
withString:@""];
关于ios - stringByReplacingOccurrencesOfString 方法调用不会更改我调用它的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213132/