C program to sort the words of the string

Here, we are going to learn how to sort the words of the string in C programming language?
Submitted by Nidhi, on July 23, 2021

Problem Solution:

Read a string from the user, then sort the words of strings using C program.

Program:

The source code to sort the words of the string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to sort the words of the string

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

void sortWords(char* str)
{
    int i = 0;
    int j = 0;
    int k = 0;
    int spaces = 0;

    char ptr1[50][100];
    char ptr2[50][100];
    char cmp[50];

    while (str[i]) {
        if ((str[i] == ' ') || (str[i] == ',') || (str[i] == '.'))
            spaces++;
        i++;
    }

    for (i = 0; j < strlen(str); j++) {
        if ((str[j] == ' ') || (str[j] == 44) || (str[j] == 46)) {
            ptr2[i][k] = '\0';
            i++;
            k = 0;
        }
        else
            ptr2[i][k++] = str[j];
    }

    for (i = 0; i < spaces; i++) {
        for (j = i + 1; j <= spaces; j++) {
            if ((strcmp(ptr2[i], ptr2[j]) > 0)) {
                strcpy(cmp, ptr2[i]);
                strcpy(ptr2[i], ptr2[j]);
                strcpy(ptr2[j], cmp);
            }
        }
    }

    printf("String after sorting is:\n");
    for (i = 0; i <= spaces; i++)
        printf("%s ", ptr2[i]);
    printf("\n");
}

int main()
{
    char str[65];

    printf("Enter string: ");
    scanf("%[^\n]s", str);

    sortWords(str);
    return 0;
}

Output:

RUN 1:
Enter string: This is my laptop which is the best
String after sorting is:
This best is is laptop my the which

RUN 2:
Enter string: Is Are Am
String after sorting is:
Am Are Is 

RUN 3:
Enter string: banana cat apple
String after sorting is:
apple banana cat

Explanation:

In the above program, we created two functions sortWords() and main(). The sortWords() function is used to sort the words of a string.

In the main() function, we read a string from the user and sort the words of string using the sortWords() function and print the sorted string on the console screen.

C String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.