c语言如何删除重复字符
时间: 2024-06-22 17:02:13 浏览: 13
在C语言中,删除字符串中的重复字符可以通过遍历字符串、使用字符数组和一个临时存储不重复字符的数组或集合(如哈希表)来实现。这里是一个简单的示例,使用字符数组来完成这个任务:
```c
#include <stdio.h>
#include <string.h>
// 声明一个字符数组来暂存不重复字符
#define SIZE 100 // 根据实际需要调整大小
char uniqueChars[SIZE];
void removeDuplicates(char* str) {
int currentIndex = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (uniqueChars[currentIndex] != str[i]) {
uniqueChars[currentIndex++] = str[i];
}
}
uniqueChars[currentIndex] = '\0'; // 添加终止符
str = '\0'; // 清空原字符串,然后将新字符串复制回去
strcpy(str, uniqueChars);
}
int main() {
char input[] = "hello world";
removeDuplicates(input);
printf("String without duplicates: %s\n", input);
return 0;
}
```
在这个示例中,`removeDuplicates` 函数遍历输入的字符串,如果遇到的字符不在 `uniqueChars` 中,就将其添加到数组的末尾。最后,将处理过的 `uniqueChars` 赋值回原始字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)