stringByReplacingOccurrencesOfString:不起作用

Gab*_*ter 0 nsstring ios

我希望我的输出为"23",但它仍显示"123".

NSString *valorTextField = [[NSString alloc] initWithFormat:@"123"];
    [valorTextField stringByReplacingOccurrencesOfString:@"1" withString:@""];
    NSLog(@"%@", valorTextField);
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 11

stringByReplacingOccurrencesOfString返回一个字符串:

NSString *valorTextField = [[NSString alloc] initWithFormat:@"123"];
NSString *replaced = [valorTextField stringByReplacingOccurrencesOfString:@"1" withString:@""];
NSLog(@"%@", replaced);
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用NSMutableString并使用该 replaceOccurrencesOfString:withString:options:range:方法.


Nig*_*ury 5

您没有valorTextField再次分配返回的字符串.你只是在执行功能.实际字符串不变.而是写:

valorTextField  = [valorTextField stringByReplacingOccurrencesOfString:@"1" withString:@""];
NSLog(@"%@", valorTextField);
Run Code Online (Sandbox Code Playgroud)