似乎字符串比较不能简单地用“==”操作来完成,因为我从解释,在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