如何用C语言找字符串中最后一个只出现一次的字符
时间: 2023-04-08 18:01:13 浏览: 118
你可以使用C语言中的循环和字符串处理函数来找到字符串中最后一个只出现一次的字符。具体步骤如下:
1. 定义一个字符变量last,用来存储最后一个只出现一次的字符。
2. 定义一个整型数组count,用来记录每个字符在字符串中出现的次数。
3. 使用循环遍历字符串中的每个字符,将其对应的count数组中的值加1。
4. 再次使用循环遍历字符串中的每个字符,如果该字符在count数组中的值为1,则将last变量更新为该字符。
5. 最后返回last变量即可。
以下是示例代码:
```c
#include <stdio.h>
#include <string.h>
char last_occurrence(char *str) {
char last = '\0';
int count[256] = {0}; // 假设字符集为ASCII码,因此定义256个元素的数组
// 统计每个字符在字符串中出现的次数
for (int i = 0; i < strlen(str); i++) {
count[(int)str[i]]++;
}
// 找到最后一个只出现一次的字符
for (int i = 0; i < strlen(str); i++) {
if (count[(int)str[i]] == 1) {
last = str[i];
}
}
return last;
}
int main() {
char str[] = "abacddbec";
char last = last_occurrence(str);
printf("最后一个只出现一次的字符是:%c\n", last);
return 0;
}
```
输出结果为:
```
最后一个只出现一次的字符是:e
```