ios Objective-C:在字符串中查找数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4663438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C: Find numbers in string
提问by Nic Hubbard
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?
想法?
回答by martin clayton
Here's an NSScannerbased 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.
- There are no digits elsewhere in the string, or if there are they are afterthe number you want to extract.
- The number won't overflow
int
.
- 数字是 0-9,没有符号,没有小数点,没有千位分隔符等。如果需要,您可以向 NSCharacterSet 添加符号字符。
- 字符串中的其他地方没有数字,或者如果有,则在您要提取的数字之后。
- 数字不会溢出
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.
回答by Zorayr
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"
- @"1234" → @"1234"
- @"001234" → @"001234"
- @"前导文本被删除 001234" → @"001234"
- @"001234 尾随文本被删除" → @"001234"
- @"a0b0c1d2e3f4" → @"001234"
Hope this helps!
希望这可以帮助!
回答by Farlei Heinen
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+”正则表达式模式):
- (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;
}
回答by Sam Ritchie
Try this answerfrom 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]];
}
}
回答by Roger
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 会更好,但我对它有点 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 Daniel Farrell
NSPredicateis the Cocoa class for parsing string using ICU regular expression.
NSPredicate是 Cocoa 类,用于使用ICU 正则表达式解析字符串。
回答by Bhavesh Patel
Swift extension for getting number from string
用于从字符串中获取数字的 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;
}
}