xcode 判断 NSString 的第一个字符是否为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5205782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:23:30  来源:igfitidea点击:

Determine if NSString's first character is a number

iphoneobjective-cxcodensstringnumbers

提问by max_

I just wanted to know how i can determine whether a NSStrings first character is a number.

我只是想知道如何确定 NSStrings 的第一个字符是否是数字。

回答by Beljoda

BOOL hasLeadingNumberInString(NSString* s) {
if (s)
    return [s length] && isnumber([s characterAtIndex:0]);
else
    return NO;

}

}

In the event you are handling many NSStrings at once (like looping through an array) and you want to check each one for formatting like leading numbers, it's better practice to include checks so that you do not try evaluating an empty or nonexistent string.

如果您一次处理多个 NSStrings(如循环遍历数组)并且您想检查每个 NSStrings 的格式,如前导数字,最好包括检查,这样您就不会尝试评估空字符串或不存在的字符串。

Example:

例子:

NSString* s = nil; //Edit: s needs to be initialized, at the very least, to nil.
hasLeadingNumberInString(s);          //returns NO
hasLeadingNumberInString(@"");        //returns NO
hasLeadingNumberInString(@"0123abc"); //returns YES

回答by Pablo Santa Cruz

Yes. You can do:

是的。你可以做:

NSString *s = ...; // a string
unichar c = [s characterAtIndex:0];
if (c >= '0' && c <= '9') {
    // you have a number!
}

回答by Anomie

I can think of two ways to do it. You could use

我可以想到两种方法来做到这一点。你可以用

[string rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location == 0

Or you could use

或者你可以使用

[[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[string characterAtIndex:0]]

回答by Ole Begemann

Check the return value of:

检查返回值:

[myString rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];

If the locationvalue of the returned range is 0, you have a match at the first character.

如果location返回范围的值为0,则您在第一个字符处匹配。

回答by Scott

Rather than using a call that scans the entire string, it is best to pull out the first char then see what it is:

与其使用扫描整个字符串的调用,不如先拉出第一个字符,然后看看它是什么:

char test = [myString characterAtIndex:0];
if (test >= '0' && test <= '9')
  return YES
else
  return NO