How to sort the words in a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
#define ROWS 6
#define COLS 10
 
int compare_function(const void *a, const void *b) {
  return strcmp(a, b);
}

char *sort_the_words_in_a_string(char s[] ) {
    char arr[ROWS][COLS];
      
    char *token = strtok(s, " ");
    int i = 0;
    while (token != NULL) {
        strcpy(arr[i++], token);
        token = strtok(NULL, " ");
    }
 
    qsort((void*)arr, (size_t)ROWS, COLS, compare_function);
     
    s[0] = '\0';
    for (int i = 0; i < ROWS; i++) {
        strcat(strcat(s, arr[i]), " ");
    }
    s[strlen(s) - 1] = '\0';
    
    return s;
}
 
int main() {
    char s[] = "php c java c++ python c#";
 
    sort_the_words_in_a_string(s);
    
    puts(s);
     
    return 0;
}

       
        
/*
run:
         
c c# c++ java php python
    
*/

 



answered Jan 18, 2021 by avibootz
edited Jul 19, 2024 by avibootz
...