【问题标题】:Take all numbers separated by spaces from a string and place in an array从字符串中取出所有以空格分隔的数字并放入数组中
【发布时间】:2016-01-24 12:14:55
【问题描述】:

我有一个格式如下的 NSString:

“Hello world 12 正在寻找一些 56”

我想找到用空格分隔的所有数字实例并将它们放在一个 NSArray 中。我不想删除这些数字。

实现这一目标的最佳方法是什么?

【问题讨论】:

  • 正则表达式。

标签: objective-c


【解决方案1】:

这是使用regular expression 的解决方案,如评论中所建议的那样。

NSString *string = @"Hello world 12 looking for some 56";

NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"\\b\\d+" options:nil error:nil];
NSArray *matches = [expression matchesInString:string options:nil range:(NSMakeRange(0, string.length))];
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in matches) {
  [result addObject:[string substringWithRange:match.range]];
}
NSLog(@"%@", result);

【讨论】:

    【解决方案2】:

    首先使用 NSString 的componentsSeparatedByString 方法创建一个数组并引用this SO question。然后迭代数组并参考这个 SO question 来检查数组元素是否为数字:Checking if NSString is Integer

    【讨论】:

    • 我目前正在使用 NSArray *a = [self.textparagraph componentsSeparatedByCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];通过数字拆分,基本上文本中的数字描述了 AVSpeechSynth 的延迟长度。遇到的每个数字也被视为一个新行,因此我可以插入 pauses 。这很好用,但我需要知道它丢弃的数值。
    【解决方案3】:

    我不知道您要在哪里执行此操作,因为根据字符串大小,它可能不会很快(例如,如果在表格单元格中调用它可能会不稳定)。

    代码:

    + (NSArray *)getNumbersFromString:(NSString *)str {
        NSMutableArray *retVal = [NSMutableArray array];
        NSCharacterSet *numericSet = [NSCharacterSet decimalDigitCharacterSet];
        NSString *placeholder = @"";
        unichar currentChar;
        for (int i = [str length] - 1; i >= 0; i--) {
            currentChar = [str characterAtIndex:i];
            if ([numericSet characterIsMember:currentChar]) {
                placeholder = [placeholder stringByAppendingString: 
                                    [NSString stringWithCharacters:&currentChar 
                                                            length:[placeholder length]+1];
            } else {
                if ([placeholder length] > 0) [retVal addObject:[placeholder intValue]];
                else placeholder = @"";
    
        return [retVal copy];
    }
    

    为了解释上面发生的事情,本质上是我,

    • 遍历每个字符,直到找到一个数字
    • 将该数字(包括后面的任何数字)添加到字符串中
    • 一旦找到一个数字,它就会将它添加到一个数组中

    希望对您有所帮助,如果需要请要求澄清

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多