2014-11-08 71 views
0

我有这样的代码:防止“stringByReplacingOccurrencesOfString”重写

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

正如你可以看到,我想做到以下几点:

  1. “+”被替换为“% 2B”
  2. ‘’替换为‘+’

当然,这是不工作作为第二线覆盖第一升ine,所以现在只有''正被替换为'+',第一行代码无效。

有没有解决这个问题的方法?

+0

只要运行在所述第一输出端的第二线,而不是“原始”。 – 2014-11-08 13:26:56

+0

@Hotlicks如果你试图说第二行和第三行代码周围,这不起作用,因为它最终忽略了前一行。我的问题的答案已经足够。 – iPwnTech 2014-11-08 13:29:31

+0

不,我是说,而不是运行第二行,并在运行第三行时将结果扔掉,使用一行的输出作为另一行的输入。 – 2014-11-08 13:30:39

回答

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

如果您有任何问题,可以使用新的NSString,以更清晰的方式执行操作:NSString * firstSept = .....,NSString * secondStep = ....,NSString * result = .....? – 2014-11-08 12:19:03

+0

更有效?它使这个和更多的工作,你可以阅读这个:“NSMutableString类添加一个基本的方法replaceCharactersInRange:withString: - 从基本的字符串处理行为继承自NSString。”在Apple文档中,您可以使用Profile。 – 2014-11-08 12:35:12

-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); 
+0

实际上使用'NSString'是最佳实践。 – zaph 2014-11-08 12:25:20

+0

@Zaph真的,你能解释一下你的理由吗?这[问题](http://stackoverflow.com/questions/7275097/when-should-we-use-nsstring-and-nsmutablestring)否则说 – 2014-11-08 12:27:55

+0

@ShamsAhmed我相信链接问题说'NSMutableString'是更有效的记忆明智的,这里是一个引用:“我期望MutableString在内存方面会稍微高效一些,因为您很早就指出程序可能会动态地需要内存.NSString可能会被分配一个适当大小的内存块。 “_ – iPwnTech 2014-11-08 12:37:25

1

简单的解决方案:

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

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

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

输出:

格式化:一些+字符串%2Bhere

+0

感谢您的回答,我现在很困惑与哪种方法一起使用,无论是使用可变对象还是不可变对象。 – iPwnTech 2014-11-08 13:00:29

+1

通常使用不可变的,它更安全。有趣的是,可变的答案是更多的代码,更多的代码不是一件好事。最佳做法#1写出最明显的代码,忽略优化。稍后如果有性能问题,那么配置文件,找到确切的问题并优化。很少的代码会导致性能问题。 – zaph 2014-11-08 13:08:00

+0

@RAStudios我会读[早熟优化](http://programmers.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil)然后看看在你的代码中,看看最适合什么 – 2014-11-08 13:17:27