isEqualToString not returning true

╄→尐↘猪︶ㄣ 提交于 2019-12-13 04:25:59

问题


The "Stopping" statement never gets printed even if you type 'stop' when running the program. Is the initWithUTF8String: method introducing extra formatting?

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    char holderText[256];

    fgets(holderText, 256, stdin);
    NSString *words = [[NSString alloc] initWithUTF8String:holderText];


    if ([words isEqualToString:@"stop"]) {

        NSLog(@"STOPPING");

    }
    NSLog(@"This is what you typed: %@", words);

    [pool drain];
    return 0;
}

回答1:


The code looks fine, even though you're leaking the words string. You need to add an [autorelease] on the end of that alloc call.

You could try initWithCString and also trim new lines and surrounding whitespace.

NSString *words = [[[NSString alloc] initWithCString:holderText] autorelease];
words = [words stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];



回答2:


fgets will include the trailing newline in the string it gives you (except in the case where it wouldn't fit in the buffer but that's not so here), so it will be "stop\n" rather than "stop".

Changing the log line to:

NSLog(@"This is what you typed: [%@]", words);

should hopefully make it clear what's happening.

Either modify the comparison to take this into account, or trim the newline off before comparing.




回答3:


Since fgets will probably include a trailing newline, you might want to do a trim of all newlines in the string by using stringByTrimmingCharactersInSet::

NSString *trimmed = [words stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

if([trimmed isEqualToString:@"stop"]]) {
  //...
}


来源:https://stackoverflow.com/questions/6025663/isequaltostring-not-returning-true

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