isEqualToString未返回true

Ali*_*Ali 0 cocoa objective-c nsstring

即使在运行程序时键入"stop",也不会打印"Stopping"语句.该initWithUTF8String:方法是否引入了额外的格式?

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;
}
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 6

fgets将在它给你的字符串中包含尾部换行符(除非它不适合缓冲区但在这里不是这样),所以它将是"stop\n"而不是"stop".

将日志行更改为:

NSLog(@"This is what you typed: [%@]", words);
Run Code Online (Sandbox Code Playgroud)

应该有希望说清楚发生了什么.

修改比较以将此考虑在内,或者在比较之前修剪换行符.