【发布时间】:2016-12-06 19:14:41
【问题描述】:
似乎字符串比较不能简单地由“==”运算符完成,因为我从 java 和 c# 中的解释中读到:
在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,这是真的。
-
如果您想知道
==的作用,在比较不同语言的字符串时,请在每种语言中查找该运算符的文档。他们都准确地解释了它的作用。