當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java String compareToIgnoreCase()用法及代碼示例


字符串 compareToIgnoreCase() 方法

compareToIgnoreCase() 是 Java 中的 String 方法,用於通過忽略大小寫的敏感性來比較兩個字符串。

如果兩個字符串相等(不考慮區分大小寫)——它返回 0,否則根據第一個不同的字符差異返回小於 0 或大於 0 的值。

用法:

    int string1.compareToIgnoreCase(string2);

這裏,string1string2是要比較的字符串,它返回一個 0、小於 0 或大於 0 的整數值。

例:

    Input:
    str1 = "Hello world!"
    str2 = "Hello world!"

    Output:
    0

    Input:
    str1 = "Hello world!"
    str2 = "HELLO WORLD!"

    Output:
    0

    Input:
    str1 = "Hello world!"
    str2 = "Hi guys!!!"

    Output:
    -4

使用 String.compareToIgnoreCase() 方法比較字符串的 Java 代碼

public class Main
{
    public static void main(String[] args) {
        String str1 = "Hello world!";
        String str2 = "Hello world!";
        String str3 = "HELLO WORLD!";
        
        System.out.println("str1 and str2 = " + str1.compareToIgnoreCase(str2));
        System.out.println("str1 and str3 = " + str1.compareToIgnoreCase(str3));
        System.out.println("str2 and str3 = " + str2.compareToIgnoreCase(str3));
        
        //checking with the condition
        if(str1.compareToIgnoreCase(str2)==0){
            System.out.println("str1 is equal to str2");
        }
        else{
            System.out.println("str1 is not equal to str2");
        }

        if(str1.compareToIgnoreCase(str3)==0){
            System.out.println("str1 is equal to str3");
        }
        else{
            System.out.println("str1 is not equal to str3");
        }        
        
        if(str2.compareToIgnoreCase(str3)==0){
            System.out.println("str2 is equal to str3");
        }
        else{
            System.out.println("str2 is not equal to str3");
        }        
        
    }
}

輸出

str1.compareToIgnoreCase(str2) = 0
str1.compareToIgnoreCase(str3) = 0
str2.compareToIgnoreCase(str3) = 0
str1 is equal to str2
str1 is equal to str3
str2 is equal to str3
public class Main
{
    public static void main(String[] args) {
        String str1 = "Hello world!";
        String str2 = "Hi guys!!!";
        
        if(str1.compareToIgnoreCase(str2)==0){
            System.out.println("str1 is equal to str2");
        }
        else{
            System.out.println("str1 is not equal to str2");
        }        
    }
}

輸出

str1 is not equal to str2


相關用法


注:本文由純淨天空篩選整理自 Java String compareToIgnoreCase() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。