似乎字符串比較不能簡單地用「==」操作來完成,因爲我從解釋,在Java和C#閱讀:差異,C++,C#和Java
在Java中,我看到這個解釋:
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
在C#中我看到這樣的代碼:
if (parametrii[0].Equals("teach"))// to check the equality of values
這是有道理的,我認爲 「==」 是檢查地址和.equal的()僅僅是檢查值。
但是我已經在Python和C++所有的時間一直在使用 「==」 我從來沒有遇到的例子
在Python中這樣的錯誤:
string1 = "helloworld"
string2 = "helloworld"
print(string1 == string2)// result true
在C++:
while(getline(ifs, line2)){
stringstream ssm(line2);
string from_stop;
string to_stop;
getline(ssm, from_stop, ',');
getline(ssm, to_stop, ',');
if(from_stop == to_stop){
adjList[from_stop].push_back(to_stop);
}
}
或
bool stop124 = false;
bool stopA24 = false;
bool stop126 = false;
for (int i = 0; i < adjVec.size(); i++) {
if (adjVec[i] == "124") stop124 = true;
else if (adjVec[i] == "A24") stopA24 = true;
else if (adjVec[i] == "126") stop126 = true;
}
這些代碼將成功編譯並獲得比較值的正確結果。我知道在C++中有一個strcmp()函數,但我很少使用它,並且不知道何時使用它而不是==來檢查兩個字符串是否相等。
所以我的問題是,這是因爲這些編程語言之間存在差異,或者只是我很幸運,我沒有遇到這些錯誤?
誰說'=='檢查參考平等?情況並非總是如此。 (至少不在c#中) –
@ M.kazemAkhgary引用引用了Java,它是真的。 – Servy
如果你想知道'=='做什麼,比較字符串時,用不同的語言,查找每種語言的該運算符的文檔。他們都解釋到底是什麼。 – Servy