Compare content of two strings in c?

5

Hi, I'm new (new programming too) and this is my first question, I would like to know how to compare two chains. This is what I did but it turns out that it does not compare me but throws me the second message no more.

char pal1[10],pal2[10];

printf("Ingrese una palabra: "); scanf("%s",pal1);
printf("Ingrese otra palabra: "); scanf("%s",pal2);

if (pal1==pal2){
    printf("\nTienen el mismo contenido!! \n%s\n%s",pal1,pal2);
}else{
    printf("\nSon cadenas de distinto contenido!! \n%s\n%s",pal1,pal2);
}
    
asked by Fede_imfeld 30.09.2017 в 01:47
source

3 answers

6

You must use strcmp () to compare strings in C.

p>
char pal1[10],pal2[10];

printf("Ingrese una palabra: "); scanf("%s",pal1);
printf("Ingrese otra palabra: "); scanf("%s",pal2);

//if (pal1==pal2){ * INCORRECTO!
if (strcmp(pal1,pal2) == 0) {
    printf("\nTienen el mismo contenido!! \n%s\n%s",pal1,pal2);
}else{
    printf("\nSon cadenas de distinto contenido!! \n%s\n%s",pal1,pal2);
}
    
answered by 30.09.2017 в 02:43
0

To compare two chains you have to go through both characters by character. In addition, the sign "==" means identity, not equality. When it is a basic type what is on the side of the sentence does have the meaning of equality, with objects and arrays does not work well. That is, pal1==pal1 is true, pal1==pal2 , is false, because even if they have the same content, they are different variables. The solution to your problem would be:

char pal1[10],pal2[10];
  int igualdad=0;

  printf("Ingrese una palabra: "); scanf("%s",pal1);
  printf("Ingrese otra palabra: "); scanf("%s",pal2);

 for (int i=0;i<10;i++){
      if(pal1[i]!=pal2[i])
        igualdad=-1;
}
if(igualdad==0)
  printf("Las palabras son identicas");
else
printf("Las palabras son distintas");

And all this last one could turn it into a procedure to which you pass both words in the following way:

public void compararPalabras(int longitud, char pal1[],char pal2[]){

 for (int i=0; i<longitud ; i++) 
{
      if(pal1[i]!=pal2[i])
        igualdad=-1;}
if(igualdad==0)
  printf("Las palabras son identicas");
 else
  printf("Las palabras son distintas");
}

The way to call this method in your program would be:

char pal1[10],pal2[10];

printf("Ingrese una palabra: "); scanf("%s",pal1);
printf("Ingrese otra palabra: "); scanf("%s",pal2);

compararPalabras(10,pal1,pal2);
    
answered by 30.09.2017 в 02:12
-3
int comparar(char cad1[],char cad2[]){
    //Cadenas iguales o distintas
    int i,j;

    do{
        for(i=0,j=0; cad1[i] !='
int comparar(char cad1[],char cad2[]){
    //Cadenas iguales o distintas
    int i,j;

    do{
        for(i=0,j=0; cad1[i] !='%pre%' && cad2[j] !='%pre%';i++,j++);
    }while(cad1[i]==cad2[j]);

    if(cad1==cad2){
        return 1;
    }else{
        return 0;
    }
}
' && cad2[j] !='%pre%';i++,j++); }while(cad1[i]==cad2[j]); if(cad1==cad2){ return 1; }else{ return 0; } }
    
answered by 22.11.2018 в 21:13