Yuvaraj.M
Yuvaraj.M

Reputation: 9811

How to find Letters,Special Characters in NSString iphone?

I'm trouble with check the Characters(a-z,A-Z) and special characters except(.) in NSString. I have a UITextField for Price, i need to pass the value for Price only Numbers with "."[Ex: Price :- 20.00]. I need to check whether any letters,special characters are in NSString, If the Characters,special characters are in NSString (UITextField text), i need to alert the user to enter valid numbers for the Field "Price.". Please help to solve this problem. Any suggestion/idea would be great. Thanks in advance.

Upvotes: 2

Views: 2190

Answers (4)

Denis
Denis

Reputation: 6413

You can try to use NSScanner class with it's scanFloat method.

NSScanner *scanner = [NSScanner scannerWithString: theString];
float scannedValue = 0.0f;

BOOL foundFloat = [scanner scanFloat:&scannedValue];
if (foundFloat && [scanner isAtEnd])
{
  // scan was successful
}
else
{
 // illegal characters were found
}

Upvotes: 1

tarmes
tarmes

Reputation: 15442

Here's one way:

if ([myString isMatchedByRegex:@"^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$"]) {
    // String is OK
}

Upvotes: 1

EXC_BAD_ACCESS
EXC_BAD_ACCESS

Reputation: 2707

You can do like this,

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
//here u can alert the user by checking length
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);


}

Upvotes: 1

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

You can use NSCharacterSet to find characters in strings:

NSCharacterSet *nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
BOOL containsNonDigitChars = [myString rangeOfCharacterFromSet:nonDigits].location == NSNotFound

Upvotes: 2

Related Questions