Comparing two strings in java character by character

mike picture mike · Aug 5, 2012 · Viewed 91.5k times · Source

I am beginner in java, I am trying to compare two strings in java char by char and find how many different chars they have by the following code but it doesn't work,

     min is the min between the 2 strings

     for(int i=0; i<min-1; i++){
            s1 = w1.substring(j,j++);
            s2 = w2.substring(j,j++);

            if (! s1.equalsIgnoreCase(s2) ){
                counter++;    
            }
      }`

Any tips?

Answer

Baz picture Baz · Aug 5, 2012

Use this:

char[] first  = w1.toLowerCase().toCharArray();
char[] second = w2.toLowerCase().toCharArray();

int minLength = Math.min(first.length, second.length);

for(int i = 0; i < minLength; i++)
{
        if (first[i] != second[i])
        {
            counter++;    
        }
}