Comparing a string from the web

一笑奈何 提交于 2019-12-24 02:25:29

问题


hey all, i'm trying to read a file on the web that says "this is a test" and i wanna compare it... so here's what i got:

NSError *error;
NSURL *theURL = [NSURL URLWithString:@"http://mysite.com/test.asp"];
NSString *test = [NSString stringWithContentsOfURL:theURL encoding:NSASCIIStringEncoding error:&error];

NSLog(@"%@",test); //prints the results.. .does work


if(test == "this is a test"){
    NSLog(@"File read");
} else {
    NSLog(@"Bad file");
}

What am i doing wrong here? I always get "Bad file" but i know it's pulling in the text. Thanks all

damien


回答1:


You need to check for nil as well & use isEqualToString function for comparison.

if(test != nil){

    if([test isEqualToString:@"this is a test"]) {
       // equal
    }
    else{
      // not equal
    }
}

else{

   NSLog(@"Bad file");

}



回答2:


If you use ==, you'll be comparing two pointers. Use isEqual: like so:

if([test isEqual: @"this is a test"]) {
    // equal
}else{
    // not equal
}



回答3:


Other than the 2 answer you can also use.

– caseInsensitiveCompare:
– localizedCaseInsensitiveCompare:
– compare:
– localizedCompare:
– compare:options:
– compare:options:range:
– compare:options:range:locale:
– localizedStandardCompare:


来源:https://stackoverflow.com/questions/5201159/comparing-a-string-from-the-web

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