C Exercise Example 79

100 Classic C Examples

Title:String sorting.

Program analysis:None.

Program source code:

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LEN 20 // Define a constant representing the maximum length of the string // Function declaration: used to swap two strings void swap(char *str1, char *str2); int main() { char str1[MAX_LEN], str2[MAX_LEN], str3[MAX_LEN]; // Prompt the user to enter strings printf("Please enter 3 strings, each ending with a newline:\n"); // Use fgets to read input and remove the newline character fgets(str1, sizeof(str1), stdin); str1[strcspn(str1, "\n")] = '\0'; // Remove the newline character fgets(str2, sizeof(str2), stdin); str2[strcspn(str2, "\n")] = '\0'; // Remove the newline character fgets(str3, sizeof(str3), stdin); str3[strcspn(str3, "\n")] = '\0'; // Remove the newline character // Sort the strings if (strcmp(str1, str2) > 0) swap(str1, str2); if (strcmp(str2, str3) > 0) swap(str2, str3); if (strcmp(str1, str2) > 0) swap(str1, str2); // Output the sorted result printf("The sorted result is:\n"); printf("%s\n%s\n%s\n", str1, str2, str3); return 0; } // Swap the contents of two strings void swap(char *str1, char *str2) { char temp[MAX_LEN]; strcpy(temp, str1); // Copy str1 to the temporary string temp strcpy(str1, str2); // Copy str2 to str1 strcpy(str2, temp); // Copy temp to str2 }

The output of running the above example is:

请输入3个字符串,每个字符串以回车结束!:
b
a
t
排序后的结果为:
a
b
t

100 Classic C Examples

other extensions