什么是更好的方法来检查一个字符串是一个整数在iPhone上? [英] What is a better way to check if a string is an integer on iPhone?

查看:112
本文介绍了什么是更好的方法来检查一个字符串是一个整数在iPhone上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将标识字符串是否为整数,即字符串只包含数字。但是,我讨厌这个代码。什么是更好的方法?

  NSString * mightBeAnInteger = fooString; 
int intValue = [fooString intValue];
if(intValue> 0
&& [NSString stringWithFormat:@%d,intValue] isEqualToString:mightBeAnInteger]){
NSLog(@mightBeAnInteger是一个整数 );
}


解决方案

[fooString rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]。location == NSNotFound 将为YES,如果字符串中只有数字字符。



请注意,这不捕获负数,因此您必须添加负号(可能通过抓取 mutableCopy 并添加符号)。


The following code will identify if a string is an integer - that is, the string contains only digits. But, I hate this code. What is a better way?

NSString *mightBeAnInteger = fooString;
int intValue = [fooString intValue];
if (intValue > 0
    && [[NSString stringWithFormat:@"%d",intValue] isEqualToString:mightBeAnInteger]) {
  NSLog(@"mightBeAnInteger is an integer");
}

解决方案

[fooString rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location == NSNotFound will be YES if the string only has number characters in it.

Note that this doesn't catch negative numbers, so you'll have to add in the negative sign (probably by grabbing a mutableCopy and adding the sign).

这篇关于什么是更好的方法来检查一个字符串是一个整数在iPhone上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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