[英]How compare two string without considering spaces and case of string in java?
I have this code: 我有以下代码:
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");
}
}
}
This example should return 11 but it returns 22. 此示例应返回11但返回22。
You can replace spaces and use equalsIgnoreCase
: 您可以替换空格并使用
equalsIgnoreCase
:
if (a.replace(" ", "").equalsIgnoreCase(b.replace(" ", ""))) {
If you want to also disregard other whitespace characters you can use replaceAll
: 如果您还想忽略其他空格字符,则可以使用
replaceAll
:
if (a.replaceAll("\\s", "").equalsIgnoreCase(b.replaceAll("\\s", ""))) {
If you want instead to check for containment , use contains
and toLowerCase
: 如果要检查是否包含 ,请使用
contains
和toLowerCase
:
if (a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase())) {
Again, if you want to disregard other whitespace character use replaceAll("\\\\s", "")
as shown above. 同样,如果要忽略其他空格字符,请使用
replaceAll("\\\\s", "")
如上所示。
Use replace()
to remove spaces, and use toLowerCase()
to bring both strings to the same case, then use contains()
: 使用
replace()
删除空格,并使用toLowerCase()
将两个字符串变成相同的大小写,然后使用contains()
:
if (a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase()))
To make this null safe (defining null
as not equal to anything, not even another null): 为了使此null安全(将
null
定义为不等于任何东西,甚至不定义另一个null):
if (a != null && b != null && a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase()))
Or, if null is considered "equal" to another null: 或者,如果null被认为与另一个null“相等”:
if (!((a == null) ^ (b == null)) || a != null && a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase()))
Try this 尝试这个
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");
}
Set both a
and b
to lowercase and remove spaces, then make your comparison: 将
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");
}
String a = " VIJ ay Kakade"; 字符串a =“ VIJ ay Kakade”; String b = " V ij ";
字符串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.