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


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

在 Java ,equalsIgnoreCase()方法String 比較兩個字符串,無論字符串的大小寫(小寫或大寫)。此方法返回一個布爾值,如果參數不為 null 並且表示忽略大小寫的等效字符串,則返回 true,否則返回 false。

equalsIgnoreCase() 的語法

str2.equalsIgnoreCase(str1);

參數

  • 字符串1:應該進行比較的字符串。

返回值

  • 一個布爾值,如果參數不為 null 並且表示等效的 String 忽略大小寫,則為 true,否則為 false。

插圖

Input : str1 = "pAwAn";
        str2 = "PAWan"
        str2.equalsIgnoreCase(str1);
Output :true

Input : str1 = "powAn";
        str2 = "PAWan"
        str2.equalsIgnoreCase(str1);
Output :false
Explanation: powan and pawan are different strings. 

Note: str1 is a string that needs to be compared with str2.

內部實施equalsIgnoreCase()方法

public boolean equalsIgnoreCase(String str) 
{    
       return (this == str) ? true    
               : (str != null)
               && (str.value.length == value.length)    
               && regionMatches(true, 0, str, 0, value.length);
}    

字符串equalsIgnoreCase()方法示例

Java


// Java Program to Illustrate equalsIgnoreCase() method
// Importing required classes
import java.lang.*;
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring and initializing strings to compare
        String str1 = "GeeKS FOr gEEks";
        String str2 = "geeKs foR gEEKs";
        String str3 = "ksgee orF geeks";
        // Comparing strings
        // If we ignore the cases
        boolean result1 = str2.equalsIgnoreCase(str1);
        // Both the strings are equal so display true
        System.out.println("str2 is equal to str1 = "
                           + result1);
        // Even if we ignore the cases
        boolean result2 = str2.equalsIgnoreCase(str3);
        // Both the strings are not equal so display false
        System.out.println("str2 is equal to str3 = "
                           + result2);
    }
}
輸出
str2 is equal to str1 = true
str2 is equal to str3 = false

相關用法


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