vijayk
vijayk

Reputation: 2753

How to compare two Strings in java without considering spaces?

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?

Upvotes: 29

Views: 99723

Answers (10)

Andrea
Andrea

Reputation: 346

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

Upvotes: 0

Kaustav Banerjee
Kaustav Banerjee

Reputation: 11

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();
}

Upvotes: 1

Cwt
Cwt

Reputation: 8576

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

Upvotes: 14

Zolt&#225;n
Zolt&#225;n

Reputation: 22156

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?

Upvotes: 23

happybuddha
happybuddha

Reputation: 1358

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

Upvotes: 1

AllTooSir
AllTooSir

Reputation: 49372

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.

Upvotes: 39

Milo Hou
Milo Hou

Reputation: 339

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

Upvotes: 2

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

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");
    }
}

Upvotes: 1

Andy Thomas
Andy Thomas

Reputation: 86411

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

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

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213263

Replace the spaces with empty string:

if (a.replace(" ", "").equalsIgnoreCase(b.replace(" ", "")))

Upvotes: 12

Related Questions