【问题标题】:Separate strings from given string从给定的字符串中分离字符串
【发布时间】:2014-10-17 08:45:38
【问题描述】:

NSString *str = @"Hello {{{separate this}}} and also this {{{ also separate this}}} world"

我需要在数组中输出:

你好 : 在数组中的索引 0

分开在数组中的索引 1

还有这个在数组中的索引 2

也分开这个在数组中的索引 3

世界在数组中的索引 4

【问题讨论】:

  • 使用 NSString 方法 [str stringByReplacingOccurrencesOfString:<#(NSString *)#> withString:<#(NSString *)#>][str componentsSeparatedByString:<#(NSString *)#>] 来实现这一点。
  • 非常感谢.....

标签: ios objective-c cocoa


【解决方案1】:

以下代码将为您提供问题中指定的结果。

注意!!! - 此代码仅适用于您的问题{{{}}} 中提到的静态符号组合。如果对该组合进行任何更改,那么您将不会获得预期的结果。

NSString *str = @"Hello {{{sepearte this}}} and also this {{{ also seperate this}}} world";

str = [str stringByReplacingOccurrencesOfString:@" {{{" withString:@"#"];
str = [str stringByReplacingOccurrencesOfString:@"}}} " withString:@"#"];
NSArray *components = [str componentsSeparatedByString:@"#"];

【讨论】:

    【解决方案2】:
    NSString *str = @"Hello group1 group1 group1 and also this group2 group2 group2 world";
    NSString *pattern = @"^Hello (.+) and also this (.+) world$";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                           options:NSRegularExpressionSearch
                                                                             error:nil];
    
    NSArray *matches = [regex matchesInString:str
                                      options:0
                                        range:NSMakeRange(0, [str length])];
    if ([matches count] == 2) {
        NSString *group1 = [str substringWithRange:[matches[0] range]];
        NSString *group2 = [str substringWithRange:[matches[1] range]];
    } else {
        NSLog(@"Match failed");
    }
    

    【讨论】:

      【解决方案3】:

      假设您的字符串格式正确,即没有任何不平衡的大括号,您可以在大括号上拆分:

      NSArray<NSString *> *components = [[str stringByReplacingOccurrencesOfString:@"}}}" withString:@"{{{"] componentsSeparatedByString:@"{{{"];
      

      然后最终修剪得到的字符串:

      NSMutableArray<NSString *> *trimmedComponents = [NSMutableArray array];
      for (NSString *component in components) {
          [trimmedComponents addObject:[component stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-08
        • 2022-11-23
        相关资源
        最近更新 更多