Objective-C中正確比較字串

來源:互聯網
上載者:User

比較兩個字串是否相等時,應該用isEqualToString:,而不能僅僅只是比較字串的指標值,例如:

NSString *thing1=@"hello 5";<br />NSString *thing2;<br />thing2=[NSString stringWithFormat:@"hello @d",5];<br />if ([thing1 isEqualToString:thing2]){<br /> NSLog(@"They are the same!")<br />}

if (thing1==thing2){<br /> NSLog(@"They are the same!")<br />}

是不同的。

這是因為==運算子只判斷thing1和thing2的指標數值,而不是他們所指的對象。由於thing1,thing2是不同的字串,所以第二種比較方式會認為它們是不同的。

有時我們想檢查兩個對象的標識:thing1和thing2是同一個對象嗎?這時就應該使用運算子==。如果是想查看等價性(即這兩個字串是否代表同一個事物嗎),那麼請使用isEqualToString: 。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.