在NSString中找到数字转换成int,方法如下。so cool !

原文地址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:
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]




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值