iPhone-替换Objective-C字符串中的多个字符?

在PHP中,我可以这样做:

$new = str_replace(array('/', ':', '.'), '', $new);

...替换所有字符/的实例。 用空白字符串(删除它们)

我可以在Objective-C中轻松做到这一点吗? 还是我必须自己动手?

目前,我正在打stringByReplacingOccurrencesOfString的多个电话:

strNew = [strNew stringByReplacingOccurrencesOfString:@"/" withString:@""];
strNew = [strNew stringByReplacingOccurrencesOfString:@":" withString:@""];
strNew = [strNew stringByReplacingOccurrencesOfString:@"." withString:@""];

谢谢,
马特

Matt Sephton asked 2020-02-13T01:21:00Z
8个解决方案
121 votes

一种不太有效的方法:

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo

如果要更有效地执行此操作,请查看NSScanner-[NSString rangeOfCharacterFromSet: ...]

Nicholas Riley answered 2020-02-13T01:21:18Z
27 votes

在某些情况下,我认为您的方法不够好。不过,顺便说一句,我认为最好使用

[strNew setString: [strNew stringByReplacingOccurrencesOfString:@":" withString:@""]];

而不是

strNew = [strNew stringByReplacingOccurrencesOfString:@"/" withString:@""];

因为我认为您正在用NSString覆盖NSMutableString指针,这可能会导致内存泄漏。

N. R. Gresham answered 2020-02-13T01:21:47Z
7 votes

最近不得不这样做,并希望分享一种有效的方法:

(假设someText是NSString或text属性)

NSString* someText = @"1232342jfahadfskdasfkjvas12!";

(此示例将删除字符串中的数字)

[someText stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [someText length])];

请记住,您将需要使用Obj-c转义字符来转义正则表达式文字字符:

(obj-c使用双反斜杠转义特殊的正则表达式文字)

...stringByReplacingOccurrencesOfString:@"[\\\!\\.:\\/]" 

有趣的是,NSRegularExpressionSearch选项很少使用,但可以导致一些非常强大的控件:

您可以在regex101.com上找到一个不错的iOS regex教程,以及有关正则表达式的更多信息。

Tommie C. answered 2020-02-13T01:22:33Z
6 votes

本质上与上面发布的Nicholas相同,但是如果要删除除一组字符外的所有内容(例如,要删除“ ABCabc123”集中的所有内容),则可以执行以下操作:

NSString *s = @"A567B$%C^.123456abcdefg";
NSCharacterSet *doNotWant = [[NSCharacterSet characterSetWithCharactersInString:@"ABCabc123"] invertedSet];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => ABC123abc

如果只需要字母数字,则可用于去除符号等。

Stonz2 answered 2020-02-13T01:22:58Z
2 votes
+ (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;
}
Krishna Gupta answered 2020-02-13T01:23:13Z
1 votes

如果要删除的字符彼此相邻,则可以使用

stringByReplacingCharactersInRange:(NSRange) withString:(NSString *)

除此之外,我认为只使用几次相同的功能还不错。 它比创建一个大型方法以更通用的方式执行相同的操作更具可读性。

Gerard answered 2020-02-13T01:23:38Z
1 votes

这是Swift 3中使用正则表达式选项replaceOccurrences的示例。

结合使用ReplacementOccurrences和String.CompareOptions.regularExpression选项。

示例(快速3):

var x = "<Hello, [play^ground+]>"
let y = x.replacingOccurrences(of: "[\\[\\]^+<>]", with: "7", options: .regularExpression, range: nil)
print(y)

输出:

7Hello, 7play7ground777
Michael Peterson answered 2020-02-13T01:24:11Z
1 votes

在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
   }

}

这样称呼它:

aString = aString.replacingOccurrences(of:['/', ':', '.'], with:"")
Matt Green answered 2020-02-13T01:24:35Z
translate from https://stackoverflow.com:/questions/713918/replace-multiple-characters-in-a-string-in-objective-c