ios 在Objective-C中替换字符串中的一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5223701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:10:01  来源:igfitidea点击:

Replacing one character in a string in Objective-C

objective-ciosstringnsstring

提问by RanLearns

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 the character, so for example, if I want to change the 3rd character in a string from A to B - how would I code that?

我知道字符的位置,例如,如果我想将字符串中的第三个字符从 A 更改为 B - 我将如何编码?

回答by theChrisKent

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

此处的文档: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"

newText 等于“Boat”

回答by MaxEcho

NSString *str = @"123*abc";
str = [str stringByReplacingOccurrencesOfString:@"*" withString:@""];
//str now 123abc

回答by Zakaria

Here is the code:

这是代码:

[aString stringByReplacingCharactersInRange:NSMakeRange(3,1) withString:@"B"];

回答by Bourne

Use the replaceCharactersInRange: withString:message on a NSMutableStringobject.

replaceCharactersInRange: withString:NSMutableString对象上使用消息。