【问题标题】:I am trying to get the string "Mother" to replace the string "string" but I'm getting an error我正在尝试获取字符串“Mother”来替换字符串“string”,但出现错误
【发布时间】:2015-02-06 04:02:04
【问题描述】:
#import <Foundation/Foundation.h>



int main(int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc]init];

    NSString *dog=@"Hotdog? I thought you said hotfrog!";
    NSMutableString *mute;

    mute = [NSMutableString stringWithString:dog];
    NSLog(@"%@", mute);

    [mute setString:@"I am a new string "];
    NSLog(@"%@", mute);

    [mute replaceCharactersInRange: NSMakeRange(11, 12) withString: @"mother"];
    NSLog(@"%@", mute);

    [pool drain];
    return 0;
}    

【问题讨论】:

  • 它肯定会给你一个错误,因为你的 mute 字符串长度是 17 并且你的范围指示起始范围是从 11 到 23 (11+12)。

标签: objective-c replace nsstring


【解决方案1】:

你要使用的方法

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target 
                                    withString:(NSString *)replacement

所以target 将是@"string"replacement 将是@"Mother"。所以你的程序可能看起来像这样:

NSString *originalString = @"I am a new string ";
NSLog(@"Here is the original string: %@", originalString);

NSString *newString = [originalString stringByReplacingOccurrencesOfString:@"string" withString:@"Mother"];
NSLog(@"And here is the new string: %@", newString);

还列出了其他类似的方法here in the doco


注意,如果您明确想使用NSMutableString,请在您的问题中说明。


注意,doing a quick Google search 很容易找到这个答案

【讨论】:

  • 这是一个可变字符串;无需创建新对象。
  • @JoshCaswell 原来是NSString - 我说没必要把它变成NSMutableString :D
  • 您不能直接从文字创建NSMutableString。这显然是一个使用NSMutableString 试用的示例程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多