用C语言编写函数实现删除字符串中重复的后出现的字符并将内容逆置,保存到另一个字符串中。比如,abcd123AcD3,删除重复字符得abcd123AD,逆置得DA321dcba。在main函数中验证。要求:字符串在main函数中由键盘输入
时间: 2024-03-16 17:41:23 浏览: 19
好的,我会为您解答这个问题。
可以使用如下的代码实现:
```c
#include <stdio.h>
#include <string.h>
void remove_duplicate_and_reverse(char *str, char *new_str) {
int len = strlen(str);
int count[256] = {0}; // 记录每个字符出现的次数
int index[256]; // 记录每个字符最后出现的位置
for (int i = 0; i < len; i++) {
count[(unsigned char)str[i]]++;
index[(unsigned char)str[i]] = i;
}
int j = 0;
for (int i = 0; i < len; i++) {
if (count[(unsigned char)str[i]] == 1) {
new_str[j++] = str[i];
}
}
new_str[j] = '\0';
len = strlen(new_str);
for (int i = 0; i < len / 2; i++) {
char temp = new_str[i];
new_str[i] = new_str[len - i - 1];
new_str[len - i - 1] = temp;
}
}
int main() {
char str[100], new_str[100];
printf("请输入一个字符串:");
scanf("%s", str);
remove_duplicate_and_reverse(str, new_str);
printf("删除重复字符并逆置后的字符串为:%s\n", new_str);
return 0;
}
```
在函数 `remove_duplicate_and_reverse` 中,我们先遍历一遍字符串,记录每个字符出现的次数和最后出现的位置。然后再遍历一遍字符串,将只出现一次的字符加入到新字符串中。最后将新字符串逆置。
在 `main` 函数中,我们先读入字符串,然后调用 `remove_duplicate_and_reverse` 函数删除重复字符并逆置,并输出结果。
注意:本程序没有对输入进行严格的错误处理,如有需要,请自行添加。