Home > OS >  I need to organize a string in an ascending form but im not sure what is the error
I need to organize a string in an ascending form but im not sure what is the error

Time:11-25

I'm trying to organize a string but my code fails. I'm not sure what I'm doing wrong, or even if my code is close to what I'm trying to do.

void ordenar(int lengh, char string[])
{
    char aux[20];

    for (int i = 0; i < lengh; i  ) {
        for (int j = 0; j < lengh; j  ){
            if (strcmp(string[j], string[i] > 0)) {
                strcpy(aux, string[i]);
                strcpy(string[i], string[j]);
                strcpy(string[j], aux);
            }
        }
    }
}

int main()
{
    char nombre_prueba[10] = "Leandro";

    ordenar(7, nombre_prueba);

    for (int i = 0; i < 7; i  ) {
        printf("%s",nombre_prueba);
    }

    return 0;
}

I asked a friend to help, but he has the same problem.

CodePudding user response:

Your compiler should be issuing some pretty serious diagnostic messages, that you should not be ignoring. If it is quiet, you need need to turn up your compiler warning level:

  • For gcc or clang, use -Wall -Wextra
  • For MSVC, use /Wall

The strcmp function takes two strings as arguments, as const char *. In your code, string[j] and string[i] are both of type char, an integral value representing a single character in the string.

Even if you had two strings to compare, the > 0 is within the argument list of the function call, which becomes much more clear with better formatting.

strcmp(string[j], string[i] > 0)

This function is not needed to reorder the contents of a string. With an ASCII encoding, you could compare each character directly.

Note that the printf specifier %s prints a single string. This call is correct, printf("%s", nombre_prueba);, but you are repeating it seven times.

With minimal changes, your code could look like:

#include <stdio.h>

void ordenar(int lengh, char string[])
{
    for (int i = 0; i < lengh; i  ) {
        for (int j = 0; j < lengh; j  ) {
            if (string[j] > string[i]) {
                char t = string[i];
                string[i] = string[j];
                string[j] = t;
            }
        }
    }
}

int main(void)
{
    char nombre_prueba[10] = "Leandro";
    ordenar(7, nombre_prueba);
    printf("%s\n", nombre_prueba);
}

which prints Ladenor. Note that uppercase letters come before lowercase letters in the ASCII table. This creates a string in ASCIIbetical order.

  • Related