I just wanted to know how i can determine whether a NSStrings first character 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.
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.
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!
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.
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
Yes. You can do:
NSString *s = ...; // a string
unichar c = [s characterAtIndex:0];
if (c >= '0' && c <= '9') {
// you have a number!
}
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With