Comparing two strings in java character by character
Asked Answered
C

5

9

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?

Correctitude answered 5/8, 2012 at 21:54 Comment(5)
The counter is i but you never use it inside the loop and have some j instead. Why?Billie
And what makes you think substring(j, j) will return anything?Outlier
What about your code "doesn't work?" What happens when you compile it? If it compiles, does it run? If it runs, what happens? Along the way, what happens that differs from your expectations? Also, what error messages do you get, if any?Lecompte
Sorry it was j instead of i in my code, I solved the problem using char method. Thank you very muchCorrectitude
(but, do you know why your solution didn't work?)Billie
S
12

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++;    
        }
}
Smear answered 5/8, 2012 at 21:56 Comment(1)
+1 but I'd add a test on the array lengths and only iterate up to the end of the shortest.Injustice
L
8

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++;    
}
Labium answered 5/8, 2012 at 21:57 Comment(0)
S
2
int i =0;
for(char c : w1.toCharArray())){
   if(i < w2.length() && w2.charAt(i++) != c)
     counter++;
}
Sind answered 5/8, 2012 at 21:59 Comment(0)
B
1

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++;    
  }
}
Billie answered 5/8, 2012 at 22:24 Comment(0)
T
0

My notes from a java training tutorial requiring string comparison with charAt() and nested loops ... The method could easily be changed to return the non-matching characters from the source string ... but I'll leave that one up to you ... ;-)

public class SubString {

public static boolean findTarget( String target, String source ) {

    int target_len = target.length();
    int source_len = source.length();

    boolean found = false;

    for(int i = 0; ( i < source_len && !found ); ++i) {

    int j = 0;

        while( !found ) {

            if( j >= target_len ) {
                break;
            }

            /**
             * Learning Concept:
             *
             *  String target = "for";
             *  String source = "Searching for a string within a string the hard way.";
             *
             *  1 - target.charAt( j ) :
             *    The character at position 0 > The first character in 'Target' > character 'f', index 0.
             *
             *  2 - source.charAt( i + j) :
             *
             *    The source strings' array index is searched to determine if a match is found for the
             *    target strings' character index position. The position for each character in the target string
             *    is then compared to the position of the character in the source string.
             *
             *    If the condition is true, the target loop continues for the length of the target string.
             *
             *    If all of the source strings' character array element position matches the target strings' character array element position
             *    Then the condition succeeds ..
             */

            else if( target.charAt( j ) != source.charAt( i + j ) ) {
                break;
            } else {
                ++j;
                if( j == target_len ) {
                    found = true;
                }
            }
        }

    }

    return found;

}

public static void main ( String ... args ) {

String target = "for";
String source = "Searching for a string within a string the hard way.";

System.out.println( findTarget(target, source) );

}

}
Togetherness answered 1/11, 2012 at 2:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.