温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C语言字符串中的单词去重与排序

发布时间:2024-08-30 09:33:45 来源:亿速云 阅读:92 作者:小樊 栏目:编程语言

在C语言中,对字符串中的单词进行去重和排序需要一些基本的字符串操作和数据结构。以下是一个简单的示例,展示了如何实现这个功能:

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

// 比较函数,用于 qsort
int cmp(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

// 去重函数
void remove_duplicates(char *words[], int *count) {
    int i, j;
    for (i = 0; i < *count - 1; i++) {
        for (j = i + 1; j < *count; j++) {
            if (strcmp(words[i], words[j]) == 0) {
                memmove(&words[j], &words[j + 1], (*count - j - 1) * sizeof(char *));
                (*count)--;
                j--;
            }
        }
    }
}

int main() {
    char input[] = "hello world this is a test hello world";
    char *word, *saveptr;
    char *words[100]; // 假设单词数量不超过100个
    int count = 0;

    // 将输入字符串分割成单词
    word = strtok_r(input, " ", &saveptr);
    while (word != NULL) {
        words[count++] = word;
        word = strtok_r(NULL, " ", &saveptr);
    }

    // 去重
    remove_duplicates(words, &count);

    // 排序
    qsort(words, count, sizeof(char *), cmp);

    // 输出结果
    for (int i = 0; i< count; i++) {
        printf("%s ", words[i]);
    }
    printf("\n");

    return 0;
}

这个程序首先使用strtok_r函数将输入字符串分割成单词,并将它们存储在words数组中。然后,它调用remove_duplicates函数去除重复的单词,并使用qsort函数对单词进行排序。最后,它遍历并输出排序后的单词。

请注意,这个示例假设单词数量不超过100个,并且每个单词的长度不超过输入字符串的长度。在实际应用中,你可能需要根据实际情况调整这些限制。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI