Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two strings in java character by character

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?

like image 280
mike Avatar asked Aug 05 '12 21:08

mike


4 Answers

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++;    
        }
}
like image 59
Baz Avatar answered Sep 22 '22 09:09

Baz


Use the charAt(index) method and use the '==' operator for the two chars:

c1 = w1.charAt(j);
c2 = w2.charAt(j);

if (c1 == c2) ){
   counter++;    
}
like image 44
Razvan Avatar answered Sep 22 '22 09:09

Razvan


int i =0;
for(char c : w1.toCharArray())){
   if(i < w2.length() && w2.charAt(i++) != c)
     counter++;
}
like image 21
kgautron Avatar answered Sep 24 '22 09:09

kgautron


We can solve the problem with substring. But let's look at your code first:

// assuming, min is the minimum length of both strings,
// then you don't check the char at the last position
for(int j=0; j < min-1; j++) {

  // s1, s2 will always be empty strings, because j++ is post-increment:
  // it will be incremented *after* it has been evaluated
  s1 = w1.substring(j,j++);
  s2 = w2.substring(j,j++);

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

A solution based on substring could be like that:

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

  if (!s1.equalsIgnoreCase(s2) ){
    counter++;    
  }
}
like image 34
Andreas Dolk Avatar answered Sep 24 '22 09:09

Andreas Dolk