Objective-C:在字符串中查找数字 [英] Objective-C: Find numbers in string

查看:132
本文介绍了Objective-C:在字符串中查找数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

想法?

推荐答案

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

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

或者你可以直接扫描到 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.

这篇关于Objective-C:在字符串中查找数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆