English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn how to sort user input strings in alphabetical order (dictionary order)5strings are sorted.
To understand this example, you should understand the followingC programmingTopic:
#include <stdio.h> #include <string.h> int main() { char str[5][50], temp[50]; printf("Input5string: "); //Get string input for (int i = 0; i < 5; ++i) { fgets(str[i], sizeof(str[i]), stdin); } //Store strings in alphabetical order for (int i = 0; i < 5; ++i) { for (int j = i + 1; j < 5; ++j) { //Swap strings (if they are not in alphabetical order) if (strcmp(str[i], str[j]) > 0) { strcpy(temp, str[i]); strcpy(str[i], str[j]); strcpy(str[j], temp); } } } printf("\nIn alphabetical order: \n"); for (int i = 0; i < 5; ++i) { fputs(str[i], stdout); } return 0; }
Output result
Input5string: R programming JavaScript Java C programming C++ programming In alphabetical order: C programming C++ programming Java JavaScript R programming
To solve this program, a two-dimensional string named str was created. This string can accommodate up to5strings, and each string can contain at most50 character (including null character).
In the program, we use two library functions:
These functions are used to compare strings and sort them in the correct order.