29

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?

2
  • 4
    st.replace(" ","")is your friend.
    – moonwave99
    Commented Jul 31, 2013 at 15:02
  • 1
    You have a wrong name of the question. According to your example, you need not ignore spaces, but take any number of consequent spaces as equivalent. Or you'll have equivalent "VIJAY KAKADE" and "VIJAYKAKADE", too.
    – Gangnus
    Commented May 25, 2019 at 18:07

10 Answers 10

39

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.

10
  • No need of replaceAll(). replace() will do well.
    – Rohit Jain
    Commented Jul 31, 2013 at 15:03
  • replace doesn't take a regular expression.
    – arshajii
    Commented Jul 31, 2013 at 15:04
  • Your earlier code was atleast a working code, \\s+ won't work with String#replace
    – anubhava
    Commented Jul 31, 2013 at 15:05
  • 3
    @RohitJain wrong! Either you use replace() with a char sequence (" ") or replaceAll() with a regex like in this answer. Commented Jul 31, 2013 at 15:05
  • 1
    @stonedsquirrel When he said use replace, he presumably meant that the arguments should change as well.
    – arshajii
    Commented Jul 31, 2013 at 15:06
23

I think replacing all spaces with an empty string poses the danger of verifying the following situation (finding the two names equal):

String a = "ANN MARIE O'RIORDAN"
String b = "ANNMARIE O'RIORDAN"

I know I may be splitting hairs here, but I found this question while looking for a similar solution to verify SQL queries in a unit test. Because my queries are multi-line static final Strings, I wanted to make sure that I didn't miss a space anywhere.

To that end, I think replacing all whitespaces with a single space, or perhaps a special character is the safest solution - which then does require regex:

if (a.trim().replaceAll("\\s+", " ").equalsIgnoreCase(b.trim().replaceAll("\\s+", " "))) {
    // Strings equivalent
}

Thoughts?

2
  • 1
    I want to underline, that your answer is/was the only correct one. I added another way. It's interesting how all quick answer did not see that problem.
    – Cwt
    Commented Sep 13, 2015 at 13:09
  • @sevenforce - "Only correct" is a very strong phrase. Your assertion depends on reading more into the OP's intent than he or she explicitly stated. Commented Oct 12, 2018 at 14:05
14

As Zoltan correctly pointing out, all answers besides his are in fact wrong.

For using the functionality from a third party library I suggest hamcrest:

import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace;

public class Main {
    public static void main(String[] args) {
        String a = "VIJAY KAKADE";
        String b = "VIJAY    KAKADE";
        System.out.print(String.format("'%s' and '%s' matching: ", a, b));
        if (equalToIgnoringWhiteSpace(a).matches(b)) {
            System.out.println("yes");
        } else {
            System.out.println("no");
        }

        String c = "VIJAYKAKADE";
        System.out.print(String.format("'%s' and '%s' matching: ", a, c));
        if (equalToIgnoringWhiteSpace(a).matches(c)) {
            System.out.println("yes");
        } else {
            System.out.println("no");
        }
    }
}

returns:

'VIJAY KAKADE' and 'VIJAY    KAKADE' matching: yes
'VIJAY KAKADE' and 'VIJAYKAKADE' matching: no
12

Replace the spaces with empty string:

if (a.replace(" ", "").equalsIgnoreCase(b.replace(" ", "")))
1
  • 3
    What if a = "ANN MARIE" and b = "ANNMARIE"? They're not the same name, but this solution will evaluate them so. Please consider my answer below.
    – Zoltán
    Commented Dec 4, 2013 at 10:23
2

if you want to replace all whitespace, including tabs etc, you can use

a = yourOriginalString.replaceAll("\\s", "");
b = yourOriginalString.replaceAll("\\s", "");
return a.equalsIgnoreCase(b);

edit: woah ninja'd like heck

1

You can use String.replace() to remove the spaces in both strings.

  String aMod = a.replace(" ","");
  String bMod = b.replace(" ","");
  if( aMod.equalsIgnoreCase(bMod) ){
     ... 
1

String#replace() method is helpful for you.

public static void main(String[] args) {
    String a="VIJAY KAKADE";
    String b="VIJAY    KAKADE";
    a = a.replace(" ", "");
    b = b.replace(" ", "");
    if(a.equalsIgnoreCase(b)){
        System.out.println("yes");
    }else{
        System.out.println("no");
    }
}
1
  • But here you have equal to "VIJAY KAKADE" also "VIJAYKAKADE", which is not what the OP wants.
    – Gangnus
    Commented May 25, 2019 at 18:03
1
a.replace(" ","")

is your best bet. However you can use a.trim() to remove leading and trailing whitespaces if you know want to ignore only the leading and trailing whitespaces. Also the StringUtils from apache commons has many more functions to help

1
public static void main(String args[]) {
    String a = "My Name is A B";
    String b = "My Name is A    B";

    System.out.println("Match = " + equalsIgnoreSpace(a, b, false));
}

static boolean equalsIgnoreSpace(String s1, String s2, boolean matchCase) {

   String val1 = stripExtraSpaces(s1);
   String val2 = stripExtraSpaces(s2);

   if(matchCase) {
       return val1.equals(val2);
   } else {
       return val1.equalsIgnoreCase(val2);
   }
}

static String stripExtraSpaces(String s) {
    String formattedString = "";
    java.util.StringTokenizer st = new java.util.StringTokenizer(s);

    while(st.hasMoreTokens()) {
        formattedString += st.nextToken() + " ";
    }

    return formattedString.trim();
}
1
  • 1
    An explanation of what you did might help the questioner more.
    – Cpp plus 1
    Commented Feb 4, 2018 at 16:51
0

All methods that uses replaceAll could have performance problem. For each comparison, the regular expression will be parsed, another string will be constructed and modified. Only at this point will the two strings be compared. Following the old principles of computer science, it seems abominable to manipulate strings by creating a new version just for the purpose of comparison. The following solution actually performs a comparison

public static boolean equalsSpacesLenient(String s1,String s2) {
   // It should handle the case where s1 or s2 is null
   int idx1=0;
   int idx2=0;
   
   for (;;) {
      if (isSpace(s1.charAt(idx1)) && isSpace(s2.charAt(idx2))) {
         // skip any additional spaces in both strings
         do {
            idx1++;
         } while (idx1<s1.length() && isSpace(s1.charAt(idx1)));
         do {
            idx2++;
         } while (idx2<s2.length() && isSpace(s2.charAt(idx2)));
      }
      else if (s1.charAt(idx1)==s2.charAt(idx2)) {
         // The current character matches: move to the next
         idx1++;
         idx2++;
      }
      else {
          // There are two different characters: the strings are different: exit.
          return false;
      }
      
      if (idx1>=s1.length()) { // s1 has no more characters
         if (idx2<=s2.length()) {
            return true; // s2 also has no more characters and the strings are equal
         }
         else {
            return false; // s2 has more characters and therefore the strings are different
         }
      }
      else { // s1 has more characters to compare
         if (idx2<=s2.length()) {
            return false; // s2 has no more characters and therefore the strings are different
         }
          // s1 and s2 have more characters to compare: continue
      }
   }
      
} 

private static boolean isSpace(int c) {
   // I can decide here how to consider 'space' in various ways
   return Character.isSpaceChar(c);
   // return c==' ';
   // return c==' ' || c=='\t' || c=='\n' || c=='\r'; 
}

You can read more detail in this blog post Comparing two strings while ignoring repeated spaces

Not the answer you're looking for? Browse other questions tagged or ask your own question.