iOS: 如何判断字符串是否相等?

来源:互联网 发布:房地产大数据分析 编辑:程序博客网 时间:2024/05/18 00:10
在 iOS 开发中, 有时需要判断两个字符串是否相等。 对于初学者来说, 由于概念不清楚,经常出现一些诡异的错误。  

这里给出代码示例: 


NSString *strA = [NSString stringWithFormat:@"a"];

NSString *strB = [NSString stringWithFormat:@"b"];

if( strA == strB)

    NSLog(@"A is equal to B");

    else

    NSLog(@"A is not equal to B");

运行这段code, 在console 上的输出是: A is not equal to B


代码做些改动, 将 strA 与strB 设为相等。

NSString *strA = [NSString stringWithFormat:@"a"];

NSString *strB = [NSString stringWithFormat:@"a"];

if( strA == strB)

    NSLog(@"A is equal to B");

    else

    NSLog(@"A is not equal to B");

运行这段code ,你会发现, 在console上的输出仍然是 A is not equal to B 。


这时候,你开始产生怀疑, 这是为什么呢 ?

问题出在 字符串对比的语句上。


if ( strA == strB) // 这个strA, strB 是指针, 虽然字符串的内容是相同的, 但指向字符串的 指针肯定是不同的, 也不能相同啊。 (为了更好地理解字符串,需要弄清楚 指针的概念。 内存的分配。 )


//if( strA == strB)

    if ([strA isEqualToString:strB])

iOS SDK 本身 也提供了 字符串对比的方法: isEqualToString:

用这个字符串方法时, 要注意的事项: if 的后面必须 是一对括号。既然 isEqualToString: 是一个method, method 的使用 都是通过 中括号 来完成的。 


特别注意的是: 在 iOS 中,既有 (... ), 也有 [ ... ] , 二者是有差别的。 在使用时,要特别注意。

0 0
原创粉丝点击