我正在努力获得字符串"母亲"替换字符串" string"但是我收到了错误

时间:2015-02-06 04:02:05

标签: objective-c replace nsstring

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

1 个答案:

答案 0 :(得分:-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

找到的一个非常简单的答案