找出字符串是否为数字 [英] Finding out whether a string is numeric or not

查看:136
本文介绍了找出字符串是否为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何检查字符串是否仅由数字组成。我从字符串中取出一个子字符串,并想检查它是否是一个数字子字符串。

How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.

NSString *newString = [myString substringWithRange:NSMakeRange(2,3)];


推荐答案

这是一种不依赖有限的方式尝试将字符串解析为数字的精度:

Here's one way that doesn't rely on the limited precision of attempting to parse the string as a number:

NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
    // newString consists only of the digits 0 through 9
}

参见 + [NSCharacterSet decimalDigitCharacterSet] - [NSString rangeOfCharacterFromSet:]

这篇关于找出字符串是否为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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