我正在尝试获取字符串 "Mother" 来替换字符串 "string" 但出现错误

I am trying to get the string "Mother" to replace the string "string" but I'm getting an error

#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;
}    

您想使用的方法

- (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

很容易找到这个答案