【问题标题】:Removing parentheses from the string in iOS从iOS中的字符串中删除括号
【发布时间】:2013-05-28 10:08:19
【问题描述】:

我正在尝试删除 iOS 中字符串中的所有括号。看到这个 stackoverflow 帖子:how to remove spaces, brackets and " from nsarray

答案:

NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@"()"];
s = [s stringByTrimmingCharactersInSet:charsToTrim];

但这只是从mystring中删除了一个括号(()。如何删除所有这些?

我的代码如下所示:

NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@"( )"];
attributedLabel.text = [attributedLabel.text stringByTrimmingCharactersInSet:charsToTrim];
NSLog(@"%@",attributedLabel.text);

需要一些指导...

【问题讨论】:

  • 问题是,trim 方法只检查字符串的开头和结尾,而不是里面的内容。
  • 奇怪的事情。您的代码与我完美配合。 NSString *s = @"( from mystring. How to ) remove ( all of them?)"; NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@"( )"]; s = [s stringByTrimmingCharactersInSet:charsToTrim]; NSLog(@"%@", s);
  • 我正在将文本从 plist 文件传递​​给属性标签。这可能是一个原因吗?

标签: ios objective-c


【解决方案1】:

尝试使用
[[attributedLabel.text stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""];
而是。

【讨论】:

  • 首先感谢您的回复..我也试过了,但它没有删除括号..是因为我从plist文件中传递文本吗?
  • @lakesh,您是否尝试删除括号“[]”,如您在文本中询问的那样,或括号“()”,如您的代码示例所示?代码是否正在运行(尝试在相关行设置断点)?
  • 尝试:NSLog(@"%@", [[@"This (is a) test." stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString: @""]);它应该记录“这是一个测试”。
  • 那么听起来您的问题出现在其他地方。如果您从 plist 文件加载,您确定在将文本设置为剥离字符串后,您的代码不会从文件重新加载吗?
  • 不,我没有。我将 plist 文件作为字典获取,其中一个键是指我传递给属性标签的字符串...
【解决方案2】:

以下代码正在运行

NSString *str=[[NSBundle mainBundle] objectForInfoDictionaryKey:@"string"];
NSLog(@"%@",[[str stringByReplacingOccurrencesOfString:@")" withString:@""] stringByReplacingOccurrencesOfString:@"(" withString:@""]);

【讨论】:

    【解决方案3】:

    只需像下面这样操作:

    NSString *finalStr = [initialStr stringByReplacingOccurenceOfString:@"(" withString:@""];
    finalStr = [finalStr stringByReplacingOccurenceOfString:@")" withString:@""];
    

    这将删除字符串中的所有括号:我在这个开发者的blog找到了这个答案

    【讨论】:

      【解决方案4】:

      Swift 4.2 使用replacingOccurrences

      例如。从 (Pizza) 获取 Pizza

      let foodWithParentheses = "(Pizza)"
      
      let pizzaWithoutParen = foodWithParentheses.replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "")
      
      print(pizzaWithoutParen)
      // output: Pizza
      

      【讨论】:

        猜你喜欢
        • 2012-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多