如何在不考虑空格的情况下比较java中的两个字符串? [英] How to compare two Strings in java without considering spaces?

查看:336
本文介绍了如何在不考虑空格的情况下比较java中的两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个例子。

  public class Test {
public static void main(String [] args) {
String a =VIJAY KAKADE;
String b =VIJAY KAKADE;
if(a.equalsIgnoreCase(b)){
System.out.println(yes);
} else {
System.out.println(no);
}
}
}

我需要检查这些字符串不考虑空间。我该如何实现这一目标?比较它们时如何忽略字符串中的空格?

解决方案

您可以尝试通过替换所有空字符串来创建新字符串如果(a.replaceAll(\\\\ +,)。equalsIgnoreCase(b.replaceAll(b。) \\\\ +,))){
//这也会照看标签等空格。
}

然后比较。


I have one example.

public class Test {
    public static void main(String[] args) {
        String a="VIJAY KAKADE";
        String b="VIJAY    KAKADE";
        if(a.equalsIgnoreCase(b)){
            System.out.println("yes");
        }else{
            System.out.println("no");
        }
    }
}

I need to check these strings without considering spaces. How do I achieve this? How do I ignore spaces in the strings when I compare them?

解决方案

You can try to create a new string by replacing all empty spaces.

if(a.replaceAll("\\s+","").equalsIgnoreCase(b.replaceAll("\\s+",""))) {
   // this will also take care of spaces like tabs etc.
}

then compare.

这篇关于如何在不考虑空格的情况下比较java中的两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆