Compare two NSStrings

主宰稳场 提交于 2019-11-27 01:50:15

问题


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, even when they are the same, it still doesn't recognize that. The code is something like this:

NSString * aString = [self someMethodThatGetsAString];

NSString * bString;

BOOL areStringsTheSame = NO;

while (areStringsTheSame != YES) {

       bString = [self someMethodThatTakesNSStringsFromAnArrey];
       if (bString == aString) {
             areStringsTheSame = YES;
       { }

I even inserted an NSLog() and made sure that at a certain point they were the same (and as far as I know this is what == stands for...), but still it didn't get into the if to change the BOOL value.

Is there another way to do this comparison? Am I missing something?


回答1:


You can use the method isEqualToString::

if ([bString isEqualToString:aString])

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




回答2:


This approach worked for me:

if ([firstString compare:secondString] == NSOrderedSame) {
    //Do something when they are the same
} else {
    //Do something when they are different
}



回答3:


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]]];
        }
    }


来源:https://stackoverflow.com/questions/6969115/compare-two-nsstrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!