Replacing one character in a string in Objective-C

前端 未结 4 842
故里飘歌
故里飘歌 2020-11-30 07:22

Hoping somebody can help me out - I would like to replace a certain character in a string and am wondering what is the best way to do this?

I know the location of th

4条回答
  •  鱼传尺愫
    2020-11-30 07:39

    If it is always the same character you can use:

    stringByReplacingOccurrencesOfString:withString:
    

    If it is the same string in the same location you can use:

    stringByReplacingOccurrencesOfString:withString:options:range:
    

    If is just a specific location you can use:

    stringByReplacingCharactersInRange:withString:
    

    Documentation here: https://developer.apple.com/documentation/foundation/nsstring

    So for example:

    NSString *someText = @"Goat";
    NSRange range = NSMakeRange(0,1);
    NSString *newText = [someText stringByReplacingCharactersInRange:range withString:@"B"];
    

    newText would equal "Boat"

提交回复
热议问题