1. 程式人生 > 其它 >C++與java中的字串相等

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);
	}
}

輸出: