【问题标题】:stringByReplacingCharactersInRange Decreases NSString LengthstringByReplacingCharactersInRange 减少 NSString 长度
【发布时间】:2012-08-06 06:20:07
【问题描述】:

我以某种方式错误地使用了 stringByReplacingCharactersInRange,但我不明白怎么做。我的目标是将NSString 的一个字符替换为另一个字符。我这样做了很多次,但是在两次替换后它从 NSString 的末尾开始切割,我不想要这个。这是我的代码。

    NSRange firstCharRange = NSMakeRange(mi, mi); // mi is an int, indicating the index of the replaced char

    myword = [myword stringByReplacingCharactersInRange:firstCharRange withString:bb.titleLabel.text]; // myword is the string

最初myword是@"RRRRRRRR",替换第一个字符串后变成了

eRRRRRRR

然后

egRRRRRR

然后

eghRRRR // why did cut off the last character?

【问题讨论】:

    标签: iphone objective-c xcode ipad nsstring


    【解决方案1】:

    NSMakeRange()的第二个参数是长度,不是结束索引。您可能只想传入1

    【讨论】:

      【解决方案2】:

      NSString *str =@"Hardeep_Singh";

      NSLog(@"Before = %@",str);
      
      str = [str stringByReplacingOccurrencesOfString:@"_" withString:@" "];
      
      NSLog(@"After = %@",str);
      

      您可以使用它。在此我们可以将一个字符替换为 NSString 的另一个字符。 可能对你有帮助。

      NSString *myword=[NSString stringWithString:@"0123456789"];
      
      NSLog(@"Before = %@ ",myword);
      
      NSRange firstCharRange = NSMakeRange(1,2); 
      

      // 第一个参数是起点,第二个是终点,从0开始,以此类推。

      myword = [myword stringByReplacingCharactersInRange:firstCharRange withString:@"H"];
      
      NSLog(@"After = %@ ",myword);
      

      这是你的答案可能是你的理解。

      【讨论】:

        猜你喜欢
        • 2017-02-09
        • 1970-01-01
        • 1970-01-01
        • 2016-05-06
        • 2014-12-31
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 2011-09-22
        相关资源
        最近更新 更多