Objective-C:在字符串中查找数字

时间:2022-10-05 19:19:12

I have a string that contains words as well as a number. How can I extract that number from the string?

我有一个包含单词和数字的字符串。如何从字符串中提取那个数字?

NSString *str = @"This is my string. #1234";

I would like to be able to strip out 1234 as an int. The string will have different numbers and words each time I search it.

我想去掉1234作为int类型,每次搜索时字符串都会有不同的数字和单词。

Ideas?

想法吗?

7 个解决方案

#1


95  

Here's an NSScanner based solution:

这里有一个基于NSScanner的解决方案:

// Input
NSString *originalString = @"This is my string. #1234";

// Intermediate
NSString *numberString;

NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

// Throw away characters before the first number.
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];

// Collect numbers.
[scanner scanCharactersFromSet:numbers intoString:&numberString];

// Result.
int number = [numberString integerValue];

(Some of the many) assumptions made here:

(其中一些)这里的假设:

  • Number digits are 0-9, no sign, no decimal point, no thousand separators, etc. You could add sign characters to the NSCharacterSet if needed.
  • 数字是0-9,没有符号,没有小数点,没有千位分隔符等等。如果需要,可以在ns字符集中添加符号字符。
  • There are no digits elsewhere in the string, or if there are they are after the number you want to extract.
  • 在字符串的其他地方没有数字,或者如果有,它们在您想要提取的数字之后。
  • The number won't overflow int.
  • 数字不会溢出int。

Alternatively you could scan direct to the int:

也可以直接扫描到int:

[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
int number;
[scanner scanInt:&number];

If the # marks the start of the number in the string, you could find it by means of:

如果#标记字符串中数字的开始,您可以通过以下方法找到它:

[scanner scanUpToString:@"#" intoString:NULL];
[scanner setScanLocation:[scanner scanLocation] + 1];
// Now scan for int as before.

#2


40  

Self contained solution:

自包含的解决方案:

+ (NSString *)extractNumberFromText:(NSString *)text
{
  NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
  return [[text componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
}

Handles the following cases:

处理以下情况:

  • @"1234" → @"1234"
  • @“1234”→@“1234”
  • @"001234" → @"001234"
  • @“001234”→@“001234”
  • @"leading text get removed 001234" → @"001234"
  • @“领先的文本删除001234”→@“001234”
  • @"001234 trailing text gets removed" → @"001234"
  • @“001234后文本被删除”→@“001234”
  • @"a0b0c1d2e3f4" → @"001234"
  • @“a0b0c1d2e3f4”→@“001234”

Hope this helps!

希望这可以帮助!

#3


3  

Try this answer from Stack Overflow for a nice piece of C code that will do the trick:

尝试一下Stack Overflow的答案,找到一段不错的C代码,就可以做到:

for (int i=0; i<[str length]; i++) {
        if (isdigit([str characterAtIndex:i])) {
                [strippedString appendFormat:@"%c",[str characterAtIndex:i]];
        }
}

#4


3  

You could use the NSRegularExpression class, available since iOS SDK 4.

您可以使用NSRegularExpression类,从iOS SDK 4开始就可以使用。

Bellow a simple code to extract integer numbers ("\d+" regex pattern) :

使用简单的代码提取整数(“\d+”regex模式):

- (NSArray*) getIntNumbersFromString: (NSString*) string {

  NSMutableArray* numberArray = [NSMutableArray new];

  NSString* regexPattern = @"\\d+";
  NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:regexPattern options:0 error:nil];

  NSArray* matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
  for( NSTextCheckingResult* match in matches) {
      NSString* strNumber = [string substringWithRange:match.range];
      [numberArray addObject:[NSNumber numberWithInt:strNumber.intValue]];
  }

  return numberArray; 
}

#5


1  

By far the best solution! I think regexp would be better, but i kind of sux at it ;-) this filters ALL numbers and concats them together, making a new string. If you want to split multiple numbers change it a bit. And remember that when you use this inside a big loop it costs performance!

到目前为止,这是最好的解决方案!我认为regexp会更好,但是我有点喜欢它;-)它过滤所有的数字并将它们合并在一起,形成一个新的字符串。如果你想分割多个数字,就改变一点。记住,当你在一个大循环中使用它时,它会降低性能!

    NSString *str= @"bla bla bla #123 bla bla 789";
    NSMutableString *newStr = [[NSMutableString alloc] init];;
    int j = [str length];
    for (int i=0; i<j; i++) {       
        if ([str characterAtIndex:i] >=48 && [str characterAtIndex:i] <=59) {
            [newStr appendFormat:@"%c",[str characterAtIndex:i]];
        }               
    }

    NSLog(@"%@  as int:%i", newStr, [newStr intValue]);

#6


0  

NSPredicate is the Cocoa class for parsing string using ICU regular expression.

NSPredicate是使用ICU正则表达式解析字符串的Cocoa类。

#7


0  

Swift extension for getting number from string

从字符串中获取数字的快速扩展

extension NSString {

func getNumFromString() -> String? {

    var numberString: NSString?
    let thisScanner = NSScanner(string: self as String)
    let numbers = NSCharacterSet(charactersInString: "0123456789")
    thisScanner.scanUpToCharactersFromSet(numbers, intoString: nil)
    thisScanner.scanCharactersFromSet(numbers, intoString: &numberString)
    return numberString as? String;
}
}

#1


95  

Here's an NSScanner based solution:

这里有一个基于NSScanner的解决方案:

// Input
NSString *originalString = @"This is my string. #1234";

// Intermediate
NSString *numberString;

NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

// Throw away characters before the first number.
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];

// Collect numbers.
[scanner scanCharactersFromSet:numbers intoString:&numberString];

// Result.
int number = [numberString integerValue];

(Some of the many) assumptions made here:

(其中一些)这里的假设:

  • Number digits are 0-9, no sign, no decimal point, no thousand separators, etc. You could add sign characters to the NSCharacterSet if needed.
  • 数字是0-9,没有符号,没有小数点,没有千位分隔符等等。如果需要,可以在ns字符集中添加符号字符。
  • There are no digits elsewhere in the string, or if there are they are after the number you want to extract.
  • 在字符串的其他地方没有数字,或者如果有,它们在您想要提取的数字之后。
  • The number won't overflow int.
  • 数字不会溢出int。

Alternatively you could scan direct to the int:

也可以直接扫描到int:

[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
int number;
[scanner scanInt:&number];

If the # marks the start of the number in the string, you could find it by means of:

如果#标记字符串中数字的开始,您可以通过以下方法找到它:

[scanner scanUpToString:@"#" intoString:NULL];
[scanner setScanLocation:[scanner scanLocation] + 1];
// Now scan for int as before.

#2


40  

Self contained solution:

自包含的解决方案:

+ (NSString *)extractNumberFromText:(NSString *)text
{
  NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
  return [[text componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
}

Handles the following cases:

处理以下情况:

  • @"1234" → @"1234"
  • @“1234”→@“1234”
  • @"001234" → @"001234"
  • @“001234”→@“001234”
  • @"leading text get removed 001234" → @"001234"
  • @“领先的文本删除001234”→@“001234”
  • @"001234 trailing text gets removed" → @"001234"
  • @“001234后文本被删除”→@“001234”
  • @"a0b0c1d2e3f4" → @"001234"
  • @“a0b0c1d2e3f4”→@“001234”

Hope this helps!

希望这可以帮助!

#3


3  

Try this answer from Stack Overflow for a nice piece of C code that will do the trick:

尝试一下Stack Overflow的答案,找到一段不错的C代码,就可以做到:

for (int i=0; i<[str length]; i++) {
        if (isdigit([str characterAtIndex:i])) {
                [strippedString appendFormat:@"%c",[str characterAtIndex:i]];
        }
}

#4


3  

You could use the NSRegularExpression class, available since iOS SDK 4.

您可以使用NSRegularExpression类,从iOS SDK 4开始就可以使用。

Bellow a simple code to extract integer numbers ("\d+" regex pattern) :

使用简单的代码提取整数(“\d+”regex模式):

- (NSArray*) getIntNumbersFromString: (NSString*) string {

  NSMutableArray* numberArray = [NSMutableArray new];

  NSString* regexPattern = @"\\d+";
  NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:regexPattern options:0 error:nil];

  NSArray* matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
  for( NSTextCheckingResult* match in matches) {
      NSString* strNumber = [string substringWithRange:match.range];
      [numberArray addObject:[NSNumber numberWithInt:strNumber.intValue]];
  }

  return numberArray; 
}

#5


1  

By far the best solution! I think regexp would be better, but i kind of sux at it ;-) this filters ALL numbers and concats them together, making a new string. If you want to split multiple numbers change it a bit. And remember that when you use this inside a big loop it costs performance!

到目前为止,这是最好的解决方案!我认为regexp会更好,但是我有点喜欢它;-)它过滤所有的数字并将它们合并在一起,形成一个新的字符串。如果你想分割多个数字,就改变一点。记住,当你在一个大循环中使用它时,它会降低性能!

    NSString *str= @"bla bla bla #123 bla bla 789";
    NSMutableString *newStr = [[NSMutableString alloc] init];;
    int j = [str length];
    for (int i=0; i<j; i++) {       
        if ([str characterAtIndex:i] >=48 && [str characterAtIndex:i] <=59) {
            [newStr appendFormat:@"%c",[str characterAtIndex:i]];
        }               
    }

    NSLog(@"%@  as int:%i", newStr, [newStr intValue]);

#6


0  

NSPredicate is the Cocoa class for parsing string using ICU regular expression.

NSPredicate是使用ICU正则表达式解析字符串的Cocoa类。

#7


0  

Swift extension for getting number from string

从字符串中获取数字的快速扩展

extension NSString {

func getNumFromString() -> String? {

    var numberString: NSString?
    let thisScanner = NSScanner(string: self as String)
    let numbers = NSCharacterSet(charactersInString: "0123456789")
    thisScanner.scanUpToCharactersFromSet(numbers, intoString: nil)
    thisScanner.scanCharactersFromSet(numbers, intoString: &numberString)
    return numberString as? String;
}
}