比较网络中的字符串

时间:2011-03-05 02:11:50

标签: iphone ios4

嘿所有,我正在尝试在网上阅读一个文件,上面写着“这是一个测试”,我想比较一下...所以这就是我得到的:

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");
}

我在这里做错了什么?我总是得到“坏文件”,但我知道它正在拉动文本。谢谢大家

达明

3 个答案:

答案 0 :(得分:4)

你需要检查nil以及&使用isEqualToString函数进行比较。

if(test != nil){

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

else{

   NSLog(@"Bad file");

}

答案 1 :(得分:0)

如果你使用==,你将比较两个指针。像这样使用isEqual:

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

答案 2 :(得分:0)

除了2个答案,你也可以使用。

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