[英]How compare two string without considering spaces and case of string in java?
我有以下代碼:
public class TestString {
public static void main(String[] args) {
String a = "Vijay Kakade";
String b = "vij";
if (a.contains(b)) {
System.out.println("11");
} else {
System.out.println("22");
}
}
}
此示例應返回11但返回22。
您可以替換空格並使用equalsIgnoreCase
:
if (a.replace(" ", "").equalsIgnoreCase(b.replace(" ", ""))) {
如果您還想忽略其他空格字符,則可以使用replaceAll
:
if (a.replaceAll("\\s", "").equalsIgnoreCase(b.replaceAll("\\s", ""))) {
如果要檢查是否包含 ,請使用contains
和toLowerCase
:
if (a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase())) {
同樣,如果要忽略其他空格字符,請使用replaceAll("\\\\s", "")
如上所示。
使用replace()
刪除空格,並使用toLowerCase()
將兩個字符串變成相同的大小寫,然后使用contains()
:
if (a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase()))
為了使此null安全(將null
定義為不等於任何東西,甚至不定義另一個null):
if (a != null && b != null && a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase()))
或者,如果null被認為與另一個null“相等”:
if (!((a == null) ^ (b == null)) || a != null && a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase()))
嘗試這個
String a = "V i jay Kakade";
String b = "vI j";
if (a.toLowerCase().replaceAll("\\s", "").trim().contains(b.trim().toLowerCase().replaceAll("\\s", ""))) {
System.out.println("11");
} else {
System.out.println("22");
}
將a
和b
都設置為小寫並刪除空格,然后進行比較:
String a = " V I J a y Kakade";
String b = " V i j ";
a = a.toLowerCase().replaceAll("\\s","");
b = b.toLowerCase().replaceAll("\\s","");
if (a.contains(b)) {
System.out.println("11");
} else {
System.out.println("22");
}
字符串a =“ VIJ ay Kakade”; 字符串b =“ V ij”;
a = a.toLowerCase().replaceAll("\\s","");
b = b.toLowerCase().replaceAll("\\s","");
if (a.contains(b)) {
System.out.println("11");
} else {
System.out.println("22");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.