开发者

Validate NSString

I am validating an NSString to e开发者_Go百科nsure that the string does not contain apostrophes.

The code I'm using to do this is

NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:@"'"];
NSScanner * scanner = [NSScanner scannerWithString:string];
NSString  * scannerResult;
[scanner setCharactersToBeSkipped:nil];
[scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult];
if(![string isEqualToString:scannerResult])
{
    return 2;
}

Returning 2 represents an error. This code works, except for the case where the string is an apostrophe.

To get around this issue, I added the following code above the preceding block.

if([string isEqualToString:@"'"]);
{
    return 2;
}

This code is evaluating to true, regardless of the input. I need to either prevent the first block from crashing with the input of ', or get the second block to work.

What am I missing?


There's no logical reason why the isEqualToString: test should always succeed. If that's your actual, copy-pasted code, you must have an error somewhere else in the function.

At any rate, it would be much simpler to test if the location of [string rangeOfString:@"'"] is NSNotFound.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜