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

#define MAX_STRING_LENGTH 100 // 最大字符串长度

int main() { char input[MAX_STRING_LENGTH]; // 输入字符串 char words[100][MAX_STRING_LENGTH]; // 存储单词的数组 int count = 0; // 单词数量

// 循环读入字符串,直到遇到回车符
while (fgets(input, MAX_STRING_LENGTH, stdin) != NULL) {
    // 去掉字符串末尾的回车符
    input[strcspn(input, "\n")] = '\0';

    // 判断是否为空字符串,如果是则跳过
    if (strlen(input) == 0) {
        continue;
    }

    // 将字符串按空格分割成单词
    char *token = strtok(input, " ");
    while (token != NULL) {
        // 将单词存入数组中
        strcpy(words[count], token);
        count++;

        // 继续分割
        token = strtok(NULL, " ");
    }
}

// 对单词数组进行排序
for (int i = 0; i < count - 1; i++) {
    for (int j = i + 1; j < count; j++) {
        if (strcmp(words[i], words[j]) > 0) {
            char temp[MAX_STRING_LENGTH];
            strcpy(temp, words[i]);
            strcpy(words[i], words[j]);
            strcpy(words[j], temp);
        }
    }
}

// 输出排序后的单词
for (int i = 0; i < count; i++) {
    printf("%s\n", words[i]);
}

return 0;

}

C语言字符串排序:按首字母字典序排列

原文地址: https://www.cveoy.top/t/topic/omec 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录