Compare two NSStrings

前端 未结 3 519
慢半拍i
慢半拍i 2020-12-09 02:54

In my app there is a mechanism that requires that at a certain point two NSStrings will be the same to do something; for some reason when I compare the two, eve

相关标签:
3条回答
  • 2020-12-09 03:35

    Recently I was shocked by the fact that two NSStrings that resemble each other on NSLog may be different. It is because sometimes NSString can contain a zero width space character. Be aware of that and consider:

    #define ZERO_WIDTH_SPACE_STRING @"\u200B"
    

    To conquer this you should clean your string from zero width white space characters before comparing:

    NSMutableString *eMailToAdd = [NSMutableString string];
    
    NSMutableCharacterSet *charSet = [[NSCharacterSet whitespaceCharacterSet] mutableCopy];
        //[charSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
    
        NSString *rawStr = [[tokenField textField] text];
        for (int i = 0; i < [rawStr length]; i++)
        {
            if (![charSet characterIsMember:[rawStr characterAtIndex:i]])
            {
                [eMailToAdd appendFormat:@"%@",[NSString stringWithFormat:@"%c", [rawStr characterAtIndex:i]]];
            }
        }
    
    0 讨论(0)
  • 2020-12-09 03:43

    This approach worked for me:

    if ([firstString compare:secondString] == NSOrderedSame) {
        //Do something when they are the same
    } else {
        //Do something when they are different
    }
    
    0 讨论(0)
  • 2020-12-09 03:45

    You can use the method isEqualToString::

    if ([bString isEqualToString:aString])
    

    == compares the references (addresses of) the strings, and not the value of the strings.

    0 讨论(0)
提交回复
热议问题