当NSString为纯数字的时候可以用下面的方法:
//判断是否为整形:
- (BOOL)isPureInt:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
int val;
return[scan scanInt:&val] && [scan isAtEnd];
}
//判断是否为浮点形:
- (BOOL)isPureFloat:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
float val;
return[scan scanFloat:&val] && [scan isAtEnd];
}
更复杂点的Question:
I have an NSString like so:
@"200hello" or @"0 something"
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(数字和字符排序不规则):
intvalue;
BOOL success=[[NSScannerscannerWithString:@"1000safkaj"]scanInteger:&value];
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.
NSString*string=@"123hello";
int myInt = [string intValue];
//判断是否为整形:
- (BOOL)isPureInt:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
int val;
return[scan scanInt:&val] && [scan isAtEnd];
}
//判断是否为浮点形:
- (BOOL)isPureFloat:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
float val;
return[scan scanFloat:&val] && [scan isAtEnd];
}
更复杂点的Question:
I have an NSString like so:
@"200hello" or @"0 something"
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(数字和字符排序不规则):
intvalue;
BOOL success=[[NSScannerscannerWithString:@"1000safkaj"]scanInteger:&value];
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.
NSString*string=@"123hello";
int myInt = [string intValue];