原文地址http://www.cocoachina.com/bbs/read.php?tid=84940
在NSString中找到数字转换成int,方法如下。so cool !
Question:I have an NSString like so:
[pre]
@"200hello" [/pre]or
[pre]@"0 something" [/pre]What I would like to be able to do is take the first occuring number in the NSString and convert it into an int.
So that @"200hello" would become int = 200.
and @"0 something" would become int = 0.
Answer1:
[pre]int value; BOOL success = [[NSScanner scannerWithString:@"1000safkaj"] scanInteger:&value]; [/pre]If the number is not always at the beginning:
NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
int value = [[@"adfsdg1000safkaj" stringByTrimmingCharactersInSet:nonDigits] intValue];
Answer2:
[pre]@"0 something" [/pre]What I would like to be able to do is take the first occuring number in the NSString and convert it into an int.
So that @"200hello" would become int = 200.
and @"0 something" would become int = 0.
Answer1:
[pre]int value; BOOL success = [[NSScanner scannerWithString:@"1000safkaj"] scanInteger:&value]; [/pre]If the number is not always at the beginning:
NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
int value = [[@"adfsdg1000safkaj" stringByTrimmingCharactersInSet:nonDigits] intValue];
Answer2:
If the int value is always at the beginning of the string, you can simply use intValue.
[pre]NSString *string = @"123hello"; int myInt = [string intValue];
[/pre]
[pre]NSString *string = @"123hello"; int myInt = [string intValue];