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

发布于 2024-10-11 20:21:49 字数 179 浏览 5 评论 0 原文

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

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

我希望能够将 1234 作为 int 去掉。每次我搜索该字符串时,该字符串都会有不同的数字和单词。

有想法吗?

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.

Ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

慈悲佛祖 2024-10-18 20:21:49

这是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];

其中的一些)此处做出的假设:

  • 数字为 0-9,没有符号,没有小数点,没有千位分隔符等。您可以添加符号字符如果需要的话,添加到 NSCharacterSet 中。
  • 字符串中的其他位置没有数字,或者如果有的话,它们位于要提取的数字的之后
  • 该数字不会溢出int

或者,您可以直接扫描到 int

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

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

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

Here's an NSScanner based solution:

// 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.
  • 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.

Alternatively you could scan direct to the 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.
明媚如初 2024-10-18 20:21:49

自包含解决方案:

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

处理以下情况:

  • @"1234" → @"1234"
  • @"001234" → @"001234"
  • @"前导文本被删除 001234" → @"001234"
  • @"001234 尾随文本被删除" → @ “001234”
  • @“a0b0c1d2e3f4”→@“001234”

希望这有帮助!

Self contained solution:

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

Handles the following cases:

  • @"1234" → @"1234"
  • @"001234" → @"001234"
  • @"leading text get removed 001234" → @"001234"
  • @"001234 trailing text gets removed" → @"001234"
  • @"a0b0c1d2e3f4" → @"001234"

Hope this helps!

幸福还没到 2024-10-18 20:21:49

您可以使用 NSRegularExpression 类,该类自 iOS SDK 4 起可用。

下面是一个简单的代码来提取整数("\d+" 正则表达式模式):

- (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; 
}

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

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

- (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; 
}
鹿港小镇 2024-10-18 20:21:49

尝试 Stack Overflow 上的 这个答案,以获得一段不错的 C 代码可以解决这个问题的代码:

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

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

for (int i=0; i<[str length]; i++) {
        if (isdigit([str characterAtIndex:i])) {
                [strippedString appendFormat:@"%c",[str characterAtIndex:i]];
        }
}
苍暮颜 2024-10-18 20:21:49

迄今为止最好的解决方案!我认为 regexp 会更好,但我有点 sux ;-) 这会过滤所有数字并将它们连接在一起,形成一个新字符串。如果你想拆分多个数字,请稍微更改一下。请记住,当您在大循环中使用它时,它会降低性能!

    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]);

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!

    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]);
心病无药医 2024-10-18 20:21:49

用于从字符串中获取数字的 Swift 扩展

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

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;
}
}
属性 2024-10-18 20:21:49

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文