views:

30

answers:

2

As the title. I tested NSScanner, but it passed some strange strings. (ex :123aaa). Is there any way to convert string<->number strictly?

A: 

NSScanner isn't that high-level. You'll have to validate the string yourself.

One way would be to scan characters up to the set of digits, assert that that failed, then scan the digits, then scan to the end and assert that that failed.

Peter Hosey
+1  A: 

You can easily roll your own. Test whether the entire string was scanned, or whether there are additional characters.

NSScanner *scanner = [NSScanner localizedScannerWithString:str];
int i;
if (![scanner scanInt:&i] || [scanner scanLocation] < [str length]) {
    // str contains additional characters
    ...
} else {
    // str contains only an int
    ...
}
outis
Thanks. This might work.
Eonil