Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if NSString's first character is a number

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

like image 885
max_ Avatar asked Mar 05 '11 18:03

max_


People also ask

How do you check if the first character in a string is a number?

Using the isDigit() method Therefore, to determine whether the first character of the given String is a digit. The charAt() method of the String class accepts an integer value representing the index and returns the character at the specified index.

How do you check if a string character is a number?

We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.

How do you check if the first letter of a string is number JavaScript?

To check if a character is a number, pass the character as a parameter to the isNaN() function. The function checks if the provided value is NaN (not a number). If the function returns false , then the character is a valid number. Copied!

How do you check if the first character of a string is a number python?

In Python, we may use the isdigit() function to see if a string is an integer or not. The isdigit() procedure will give True if the characters in a string are digits.


3 Answers

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.

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
like image 92
Beljoda Avatar answered Sep 23 '22 02:09

Beljoda


Yes. You can do:

NSString *s = ...; // a string
unichar c = [s characterAtIndex:0];
if (c >= '0' && c <= '9') {
    // you have a number!
}
like image 39
Pablo Santa Cruz Avatar answered Sep 22 '22 02:09

Pablo Santa Cruz


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]]
like image 45
Anomie Avatar answered Sep 23 '22 02:09

Anomie