2012-08-05 12 views
8

Soy principiante en Java, estoy tratando de comparar dos cadenas en java char por char y encuentro cuántos caracteres diferentes tienen con el siguiente código pero no funciona,Comparación de dos cadenas en carácter java por carácter

 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++;  
      } 
     }` 

¿Algún consejo?

+2

El contador es 'i' pero nunca usas está dentro del bucle y tiene algo de 'j' en su lugar. ¿Por qué? –

+0

¿Y qué te hace pensar que la subcadena (j, j) devolverá algo? – EJP

+1

¿Qué pasa con el código "no funciona"? ¿Qué pasa cuando lo compila? Si se compila, ¿se ejecuta? Si se ejecuta, ¿qué sucede? En el camino, ¿qué sucede que difiere de tus expectativas? Además, ¿qué mensajes de error obtienes, si hay alguno? –

Respuesta

9

Utilice esta:

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++;  
     } 
} 
+0

+1 pero agregaría una prueba en las longitudes de la matriz y solo iteraría hasta el final de la más corta. – fvu

+0

@fvu Bastante bien. Lo agregué. – Baz

3

Utilice el método charAt (índice) y utilizar el operador '==' para los dos caracteres:

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

if (c1 == c2)){ 
    counter++;  
} 
2
int i =0; 
for(char c : w1.toCharArray())){ 
    if(i < w2.length() && w2.charAt(i++) != c) 
    counter++; 
} 
1

Podemos resolver el problema substring. Pero vamos a ver su código en primer lugar:

// 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++;  
    } 
} 

Una solución basada en substring podría ser así:

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

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

mis notas de un tutorial de formación de Java que requiere la comparación de cadenas con charAt() y bucles anidados. .. El método podría cambiarse fácilmente para devolver los caracteres que no coinciden de la cadena fuente ... pero lo dejo a usted ... ;-)

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

} 

} 
Cuestiones relacionadas