C++与java中的字符串相等
C++中的字符串相等
string:
1.通过==
C++中的string类对操作符==实现了重载,可用来判断两字符串的内容是否相等
2.通过std::string::compare
定义:
int compare (const string& comparing_str) const;
value | relation between compared string and comparing string |
---|---|
0 | They compare equal |
0| Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.
<0|Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.
原生字符串char*
①先通过string::c_str()转换为原生c的字符串:
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
②后通过strcmp()比较两个字符串
int strcmp ( const char * str1, const char * str2 );
value | indicates |
---|---|
<0 | the first character that does not match has a lower value in ptr1 than in ptr2 |
0 | the contents of both strings are equal |
0|the first character that does not match has a greater value in ptr1 than in ptr
实验
源码:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
string s1="abc123";
string s2="abc123";
cout<<&s1<<endl;
cout<<&s2<<endl;
cout<<(s1==s2)<<endl;
cout<<s1.compare(s2)<<endl;
return 0;
}
输出:
Java中的字符串相等:
String:
1.==
比较的是两个String对象指向的地址值
2.equals()
String类重写了euqals()方法,比较的是字符串的内容
实验
源码:
public class StringTes {
public static void main(String[] args) {
String a=new String("abc123");
String b=new String("abc123");
String c="xyz";
String d="xyz";
String s1="xy";
String s2="z";
String s3=s1+s2;
System.out.println("hash codes of a and b:");
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(b));
System.out.println("a==b:");
System.out.println(a==b);
System.out.println("hash codes of c and d:");
System.out.println(System.identityHashCode(c));
System.out.println(System.identityHashCode(d));
System.out.println("hash code of s3:");
System.out.println(System.identityHashCode(s3));
System.out.println("c==d:");
System.out.println(c==d);
}
}