温馨提示×

c语言怎么删除重复字符并排序

小亿
88
2024-02-27 16:18:15
栏目: 编程语言

以下是一个示例代码,可以删除重复字符并对字符进行排序:

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

void removeDuplicatesAndSort(char* str) {
    int len = strlen(str);
    int index = 0;
    
    // Remove duplicates
    for (int i = 0; i < len; i++) {
        int j;
        for (j = 0; j < index; j++) {
            if (str[i] == str[j]) {
                break;
            }
        }
        if (j == index) {
            str[index++] = str[i];
        }
    }
    
    // Sort characters
    for (int i = 0; i < index - 1; i++) {
        for (int j = i + 1; j < index; j++) {
            if (str[i] > str[j]) {
                char temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }
    
    str[index] = '\0';
}

int main() {
    char str[] = "hello";
    
    // Remove duplicates and sort characters
    removeDuplicatesAndSort(str);
    
    printf("Result: %s\n", str);
    
    return 0;
}

在上面的示例代码中,我们首先定义了一个函数removeDuplicatesAndSort,该函数接受一个字符串作为输入,并删除重复的字符,并对字符进行排序。然后在main函数中调用这个函数,并打印处理后的结果。您可以将上面的示例代码复制粘贴到一个C文件中,然后编译运行,看看输出结果。

0