objective-c 在Objective-C中替换字符串中的多个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/713918/
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
Replace multiple characters in a string in Objective-C?
提问by Matt Sephton
In PHP I can do this:
在 PHP 中,我可以这样做:
$new = str_replace(array('/', ':', '.'), '', $new);
...to replace all instances of the characters / : . with a blank string (to remove them)
...替换字符 / : 的所有实例。用空字符串(删除它们)
Can I do this easily in Objective-C? Or do I have to roll my own?
我可以在 Objective-C 中轻松做到这一点吗?还是我必须自己滚动?
Currently I am doing multiple calls to stringByReplacingOccurrencesOfString:
目前我正在多次调用stringByReplacingOccurrencesOfString:
strNew = [strNew stringByReplacingOccurrencesOfString:@"/" withString:@""];
strNew = [strNew stringByReplacingOccurrencesOfString:@":" withString:@""];
strNew = [strNew stringByReplacingOccurrencesOfString:@"." withString:@""];
Thanks,
matt
谢谢,
马特
回答by Nicholas Riley
A somewhat inefficient way of doing this:
这样做的效率有点低的方法:
NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo
Look at NSScannerand -[NSString rangeOfCharacterFromSet: ...]if you want to do this a bit more efficiently.
看NSScanner和-[NSString rangeOfCharacterFromSet: ...],如果你想多一点有效地做到这一点。
回答by nikkumang
There are situations where your method is good enough I think matt.. BTW, I think it's better to use
在某些情况下,您的方法足够好,我认为 matt .. BTW,我认为最好使用
[strNew setString: [strNew stringByReplacingOccurrencesOfString:@":" withString:@""]];
rather than
而不是
strNew = [strNew stringByReplacingOccurrencesOfString:@"/" withString:@""];
as I think you're overwriting an NSMutableString pointer with an NSString which might cause a memory leak.
因为我认为您正在用 NSString 覆盖 NSMutableString 指针,这可能会导致内存泄漏。
回答by Tommie C.
Had to do this recently and wanted to share an efficient method:
最近不得不这样做,想分享一个有效的方法:
(assuming someText is a NSString or text attribute)
(假设 someText 是 NSString 或 text 属性)
NSString* someText = @"1232342jfahadfskdasfkjvas12!";
(this example will strip numbers from a string)
(此示例将从字符串中删除数字)
[someText stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [someText length])];
Keep in mind that you will need to escape regex literal characters using Obj-c escape character:
请记住,您需要使用 Obj-c 转义字符转义正则表达式文字字符:
(obj-c uses a double backslash to escape special regex literals)
(obj-c 使用双反斜杠来转义特殊的正则表达式文字)
...stringByReplacingOccurrencesOfString:@"[\\!\.:\/]"
What makes this interesting is that NSRegularExpressionSearch option is little used but can lead to some very powerful controls:
有趣的是 NSRegularExpressionSearch 选项很少使用,但可以产生一些非常强大的控件:
You can find a nice iOS regex tutorial hereand more on regular expressions at regex101.com
你可以找到一个不错的iOS正则表达式的教程这里在多对正则表达式regex101.com
回答by Stonz2
Essentially the same thing as Nicholas posted above, but if you want to remove everything EXCEPT a set of characters (say you want to remove everything that isn't in the set "ABCabc123") then you can do the following:
本质上与 Nicholas 上面发布的内容相同,但是如果您想删除除一组字符之外的所有内容(假设您要删除不在“ABCabc123”集合中的所有内容),那么您可以执行以下操作:
NSString *s = @"A567B$%C^.123456abcdefg";
NSCharacterSet *doNotWant = [[NSCharacterSet characterSetWithCharactersInString:@"ABCabc123"] invertedSet];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => ABC123abc
Useful in stripping out symbols and such, if you only want alphanumeric.
如果您只想要字母数字,则可用于去除符号等。
回答by Krishna Gupta
+ (NSString*) decodeHtmlUnicodeCharactersToString:(NSString*)str
{
NSMutableString* string = [[NSMutableString alloc] initWithString:str]; // #&39; replace with '
NSString* unicodeStr = nil;
NSString* replaceStr = nil;
int counter = -1;
for(int i = 0; i < [string length]; ++i)
{
unichar char1 = [string characterAtIndex:i];
for (int k = i + 1; k < [string length] - 1; ++k)
{
unichar char2 = [string characterAtIndex:k];
if (char1 == '&' && char2 == '#' )
{
++counter;
unicodeStr = [string substringWithRange:NSMakeRange(i + 2 , 2)]; // read integer value i.e, 39
replaceStr = [string substringWithRange:NSMakeRange (i, 5)]; // #&39;
[string replaceCharactersInRange: [string rangeOfString:replaceStr] withString:[NSString stringWithFormat:@"%c",[unicodeStr intValue]]];
break;
}
}
}
[string autorelease];
if (counter > 1)
return [self decodeHtmlUnicodeCharactersToString:string];
else
return string;
}
回答by Gerard
If the characters you wish to remove were to be adjacent to each other you could use the
如果要删除的字符彼此相邻,则可以使用
stringByReplacingCharactersInRange:(NSRange) withString:(NSString *)
Other than that, I think just using the same function several times isn't that bad. It is much more readable than creating a big method to do the same in a more generic way.
除此之外,我认为多次使用相同的功能并没有那么糟糕。它比创建一个大方法以更通用的方式做同样的事情更具可读性。
回答by Michael Peterson
Here is an example in Swift 3 using the regularExpression option of replacingOccurances.
这是 Swift 3 中的一个示例,它使用了替换出现次数的正则表达式选项。
Use replacingOccurrencesalong with a the String.CompareOptions.regularExpressionoption.
使用replacingOccurrences用了一起String.CompareOptions.regularExpression选项。
Example (Swift 3):
示例(Swift 3):
var x = "<Hello, [play^ground+]>"
let y = x.replacingOccurrences(of: "[\[\]^+<>]", with: "7", options: .regularExpression, range: nil)
print(y)
Output:
输出:
7Hello, 7play7ground777
回答by Matt Green
Create an extension on String...
在字符串上创建扩展...
extension String {
func replacingOccurrences(of strings:[String], with replacement:String) -> String {
var newString = self
for string in strings {
newString = newString.replacingOccurrences(of: string, with: replacement)
}
return newString
}
}
Call it like this:
像这样调用它:
aString = aString.replacingOccurrences(of:['/', ':', '.'], with:"")

