Print strings in alphabetical order

Asked

Viewed 29,520 times

2

I’m trying to do here because the user provides 3 name at least so I have to sort these names in alphabetical order, had tried with strcmp, but I didn’t really understand the concept of this command. So I used the following code:

char nm1[20], nm2[20], nm3[20], cont;
        char alf[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','w','y','z'};
        char alfb[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','W','Y','Z'};
        printf("Nome 1: ");
        scanf("%s", &nm1);
        printf("Nome 2: ");
        scanf("%s", &nm2);
        printf("Nome 3: ");
        scanf("%s", &nm3);

        for(cont = 0; cont < 26; cont++){
            if(nm1[0] == alf[cont]|| nm1[0] == alfb[cont])
                printf("- %s", nm1);
            if(nm2[0] == alf[cont]|| nm2[0] == alfb[cont])
                printf("- %s", nm2);
            if(nm3[0] == alf[cont]|| nm3[0] == alfb[cont])
                printf("- %s", nm3);    
        }

It compares the first letter of each name and prints if it equals the letter they are reading from the alphabet. But so it only sorts by the first letter of the name, if the user type ana, andre e adão it will print in the same order and not in the correct alphabetical order

4 answers

4


The function strcmp() takes two string to be compared and will have 3 possible returns:

  • less than 0: when you find a different character in the strings and that character of the former String for minor that of the second String. (before)

  • equal to 0: when they’re equal.

  • greater than 0: when you find a different character in the strings and that character of the first String for greater that of the second String. (afterward)

I suggest you switch your three variables to an array of char, this way it will be very simple to order.

char nm[3][20], aux[20];

for (i = 0; i < 3; i++) {
   printf("\nNome %i: ", i+1);
   scanf("%s", nm[i]);
}


for (i = 1; i < 3; i++) { /* 3 = qtde de palavras */
   for (j = 1; j < 3; j++) {
      // verifica se tem que ser depois, se for troca de posição
      if (strcmp(nm[j - 1], nm[j]) > 0) {
         strcpy(aux, nm[j - 1]);
         strcpy(nm[j - 1], nm[j]);
         strcpy(nm[j], aux);
      }
   }
}

// só mostrar a matriz
for (i = 0; i < 3; i++)
   printf("\n%s", nm[i]);

Remember to give include in <string.h>.

3

The strcmp() returns one of three hypotheses.

cmp = strcmp(n1, n2);
if (cmp == 0) /* n1 igual a n2 */;
if (cmp < 0) /* n1 menor que n2 */;
if (cmp > 0) /* n1 maior que n2 */;

As long as you remember this, the use of strcmp is nothing special.

To compare names, you have to convert everything to minute (or upper case) before comparing: a cycle with tolower() solves this problem.

In pseudo code

obter nm1, nm2, nm3
converter nm1, nm2, e nm3 para minusculas,
      possivelmente com copia para nao perder a informacao original
trocar nm1 e nm2?
trocar nm2 e nm3?
trocer nm1 e nm2?
imprimir (as copias originais de) nm1, nm2, e nm3

2

I’m going to post a possible answer, it’s a simple algorithm that sorts words using selectSort, qtd is the amount of words and tam is the size of the words.

# include<stdio.h>
const int qtd = 10;
const int tam = 30;
main()
{
    int i, j, x, menor;
    char a[qtd][tam], aux[qtd];
    for(i = 0; i < qtd; i++)
    {
        printf("Informe o %d° nome: ", i + 1);
        scanf("%s", a[i]);
    }
        for(i = 0; i < qtd - 1; i++)
        {
                x = 0;
                menor = i;
                for(j = i + 1; j < qtd; j++)
                {
                    x = 0;
                    while(a[menor][x] == a[j][x])
                    {
                            x++;
                    } 
                    if(a[menor][x] > a[j][x])
                    {
                         menor = j;
                    }
                }
                if(menor != i)
                {
                        strcpy(aux, a[menor]);
                        strcpy(a[menor], a[i]);
                        strcpy(a[i], aux);
                }
        }
        for(i = 0; i < qtd; i++)
        {
                printf("%s%c", a[i], 10);
        }
}

0

/* Ordenar vetor alfabeticamente*/

# include <stdio.h>
# include<stdlib.h>
# include <string.h>

int main (){

char nome[3][100], copia[100];

int i, j;

/* A variável nome armazena 3 nomes com até 100 caracteres.

A variável copia é apenas uma auxiliar que recebe 100 caracteres
*/

//Entrada dos nomes

for ( i = 0; i < 3; i ++){
   printf ( "Informe o nome: " );
   gets ( nome[i] );
}

//A troca alfabeticamente

for ( i = 0; i < (3-1) ; i ++ ) 
   for( j = i + 1; j < 3; j ++ )

/* strcmp 
     retorna = 0, caso a = b
     retorna > 0, caso a > b
     retorna < 0, caso a < b
*/

      if ( strcmp( nome[i], nome[j] ) > 0 ){
/* strcpy
       copia de string 
       strcpy ( VarRecebe, VarEntrega )
*/
          strcpy ( copia, nome[i] );
         strcpy( nome[i], nome[j] );
         strvpy( nome[j], copia) ;
}


/* Apresentação do vetor

Essa eu deixo para que finalizes, ou seja para que a gente não faça tudo. 
Acredito que sabes a lógica para apresentar um determinado vetor, portanto só tens de colocá-la abaixo . 

NB: Considerando que o vetor é nome[] e não nome[][]
*/


}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.