ios Objective-C 中的字符串替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/668228/
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
String replacement in Objective-C
提问by 4thSpace
How to replace a character is a string in Objective-C?
如何在Objective-C中替换一个字符是一个字符串?
回答by epatel
You could use the method
你可以用这个方法
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement
...to get a new string with a substring replaced (See NSString
documentation for others)
...获取替换了子字符串的新字符串(请参阅NSString
其他文档)
Example use
示例使用
NSString *str = @"This is a string";
str = [str stringByReplacingOccurrencesOfString:@"string"
withString:@"duck"];
回答by mipadi
NSString
objects are immutable (they can't be changed), but there is a mutable subclass, NSMutableString
, that gives you several methods for replacing characters within a string. It's probably your best bet.
NSString
对象是不可变的(它们不能更改),但是有一个可变子类NSMutableString
,它为您提供了几种替换字符串中字符的方法。这可能是你最好的选择。
回答by tania_S
If you want multiple string replacement:
如果您想要多个字符串替换:
NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo
回答by Marlon Ruiz
It also posible string replacement with stringByReplacingCharactersInRange:withString:
它还可以用 stringByReplacingCharactersInRange:withString 替换字符串:
for (int i = 0; i < card.length - 4; i++) {
if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {
NSRange range = NSMakeRange(i, 1);
card = [card stringByReplacingCharactersInRange:range withString:@"*"];
}
} //out: **** **** **** 1234
回答by Shaik Tamim
NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];
回答by Meir
The problem exists in old versions on the iOS. in the latest, the right-to-left works well. What I did, is as follows:
iOS 上的旧版本存在此问题。最近,从右到左的效果很好。我所做的如下:
first I check the iOS version:
首先我检查iOS版本:
if (![self compareCurVersionTo:4 minor:3 point:0])
Than:
比:
// set RTL on the start on each line (except the first)
myUITextView.text = [myUITextView.text stringByReplacingOccurrencesOfString:@"\n"
withString:@"\u202B\n"];