防止'stringByReplacingOccurrencesOfString'覆盖

时间:2014-11-08 11:47:33

标签: objective-c iphone ios8

我有这段代码:

NSString *formatted = original;
formatted = [original stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
formatted = [original stringByReplacingOccurrencesOfString:@" " withString:@"+"];

正如您可能看到的那样,我正在尝试执行以下操作:

  1. '+'替换为'%2B'
  2. ''替换为'+'
  3. 当然,这不起作用,因为第二行会覆盖第一行,所以现在只有''被'+'替换,第一行代码无效。

    有解决方法吗?

3 个答案:

答案 0 :(得分:2)

NSString *formatted = original;
formatted = [formatted stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
formatted = [formatted stringByReplacingOccurrencesOfString:@" " withString:@"+"];

答案 1 :(得分:1)

简单的解决方案:

NSString *original = @"some string+here";

NSString *formatted = [original stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
formatted = [formatted stringByReplacingOccurrencesOfString:@" " withString:@"+"];

NSLog(@"formatted: %@", formatted);

输出:

  

格式化:some + string%2Bhere

答案 2 :(得分:-1)

最好的方法是使用Mutable string对象而不是不可变对象,因为每次更换字符串时都必须在内存中创建一个新对象,这会导致编码错误。

   NSString *original = @"some string here";

    /**
     *  Create a Mutable string object as you will always be changing its value depending on the request
     */
    NSMutableString *newString = [NSMutableString stringWithString:original];

    /**
     *  replace all occurrences within the current object
     */
    [newString replaceOccurrencesOfString:@"+"
                               withString:@"%2B"
                                  options:NSCaseInsensitiveSearch range:NSMakeRange(0, newString.length)];

    [newString replaceOccurrencesOfString:@" "
                               withString:@"+"
                                  options:NSCaseInsensitiveSearch range:NSMakeRange(0, newString.length)];

    NSLog(@"Result: %@", newString);