开发者

isEqualToString not returning true

开发者 https://www.devze.com 2023-03-06 04:02 出处:网络
The \"Stopping\" statement never gets printed even if you type \'stop\' when running the program. Is the initWithUTF8String: method introducing extra formatting?

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"开发者_如何学Python]) {

        NSLog(@"STOPPING");

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

    [pool drain];
    return 0;
}


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.


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"]]) {
  //...
}


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

精彩评论

暂无评论...
验证码 换一张
取 消