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?
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++;
}
}
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++;
}
int i =0;
for(char c : w1.toCharArray())){
if(i < w2.length() && w2.charAt(i++) != c)
counter++;
}
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++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With