Java 比較字符串
示例 1 : 是否是同一個對象
str1和str2的內容一定是一樣的!
但是,並不是同一個字符串對象
package character;
public class TestString {
public static void main(String[] args) {
String str1 = "the light";
String str2 = new String(str1);
//==用於判斷是否是同一個字符串對象
System.out.println( str1 == str2);
}
}
示例 2 : 是否是同一個對象-特例
str1 = "the light";
str3 = "the light";
一般說來,編譯器每碰到一個字符串的字面值,就會創建一個新的對象
所以在第6行會創建了一個新的字符串"the light"
但是在第7行,編譯器發現已經存在現成的"the light",那么就直接拿來使用,而沒有進行重復創建
package character;
public class TestString {
public static void main(String[] args) {
String str1 = "the light"; //第6行
String str3 = "the light"; //第7行
System.out.println( str1 == str3);
}
}
示例 3 : 內容是否相同
使用equals進行字符串內容的比較,必須大小寫一致
equalsIgnoreCase,忽略大小寫判斷內容是否一致
package character;
public class TestString {
public static void main(String[] args) {
String str1 = "the light";
String str2 = new String(str1);
String str3 = str1.toUpperCase();
//==用於判斷是否是同一個字符串對象
System.out.println( str1 == str2);
System.out.println(str1.equals(str2));//完全一樣返回true
System.out.println(str1.equals(str3));//大小寫不一樣,返回false
System.out.println(str1.equalsIgnoreCase(str3));//忽略大小寫的比較,返回true
}
}
示例 4 : 是否以子字符串開始或者結束
startsWith //以...開始
endsWith //以...結束
package character;
public class TestString {
public static void main(String[] args) {
String str1 = "the light";
String start = "the";
String end = "Ight";
System.out.println(str1.startsWith(start));//以...開始
System.out.println(str1.endsWith(end));//以...結束
}
}
練習: 比較字符串
創建一個長度是100的字符串數組
使用長度是2的隨機字符填充該字符串數組
統計這個字符串數組里重復的字符串有多少種(忽略大小寫)
答案:
package character;
public class TestString {
public static void main(String[] args) {
String[] ss = new String[100];
// 初始化
for (int i = 0; i < ss.length; i++) {
ss[i] = randomString(2);
}
// 打印
for (int i = 0; i < ss.length; i++) {
System.out.print(ss[i] + " ");
if (19 == i % 20)
System.out.println();
}
for (String s1 : ss) {
int repeat = 0;
for (String s2 : ss) {
if (s1.equalsIgnoreCase(s2)) {
repeat++;
if (2 == repeat) {
// 當repeat==2的時候,就找打了一個非己的重復字符串
putIntoDuplicatedArray(s1);
break;
}
}
}
}
System.out.printf("總共有 %d種重復的字符串%n", pos);
if (pos != 0) {
System.out.println("分別是:");
for (int i = 0; i < pos; i++) {
System.out.print(foundDuplicated[i] + " ");
}
}
}
static String[] foundDuplicated = new String[100];
static int pos;
private static void putIntoDuplicatedArray(String s) {
for (int i = 0; i < pos; i++){
if (foundDuplicated[i].equalsIgnoreCase(s))
return;
}
foundDuplicated[pos++] = s;
}
private static String randomString(int length) {
String pool = "";
for (short i = '0'; i <= '9'; i++) {
pool += (char) i;
}
for (short i = 'a'; i <= 'z'; i++) {
pool += (char) i;
}
for (short i = 'A'; i <= 'Z'; i++) {
pool += (char) i;
}
char cs[] = new char[length];
for (int i = 0; i < cs.length; i++) {
int index = (int) (Math.random() * pool.length());
cs[i] = pool.charAt(index);
}
String result = new String(cs);
return result;
}
}