Search code examples
iosobjective-cnsstringnscharacterset

How to check a string using AND or OR logic with NSCharacterSet


I am using Zxing library to scan the Barcodes. The result is stored in an NSString. Here I am looking into two cases:

Case:'semicolon' : If the result string contains semicolon character....then store it in Semicolon Array

myWords_semicolon = [_myString componentsSeparatedByCharactersInSet:
                            [NSCharacterSet characterSetWithCharactersInString:@";,;;"]
                            ];
       //here myWords_semicolon is a NSArray

Case: 'pipe' : If the result string contains pipe character...then store it in a pipe array.

myWords_pipe = [_myString componentsSeparatedByCharactersInSet:
                    [NSCharacterSet characterSetWithCharactersInString:@"|,||"]
           ];

What I tried to do is, if the result string contains semicolon......go to case :'semicolon' ......if the result contains pipe go to case: 'pipe'. I used this to do that but couldn't get the right solution.

if ([_myString rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@";,;;"]].location != NSNotFound) {
        NSLog(@"This string doesnt contain semicolon characters");
        myWords=myWords_pipe;

    }

    if ([_myString rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"|,||"]].location != NSNotFound) {
        NSLog(@"This string doesnt contain pipe characters");


        myWords=myWords_semicolon;
    }

Here in this case....only semicolon is case is working,even though I scan pipe case ,the scanner is unable to recognize the pipe case.. Is there any other way to use && or || logic here?


Solution

  • The problem with your code is that both sets contain commas, and at the same time both strings with pipes and strings with semicolons contain commas. Therefore, only the assignment from the last of the two ifs is going to have an effect, because both ifs will "fire".

    You should be able to fix this by removing commas and duplicate pipes from your sets. Moreover, you should be able to simplify it further by using rangeOfString: method instead of rangeOfCharacterFromSet:

    if ([_myString rangeOfString:@";"].location != NSNotFound) {
        NSLog(@"This string contains a semicolon");
        myWords=myWords_semicolon;
    }
    if ([_myString rangeOfString:@"|"].location != NSNotFound) {
        NSLog(@"This string contains a pipe");
        myWords=myWords_pipe;
    }