c语言输入一个长度不超过 100 的字符串,删除串中的重复字符。
时间: 2023-07-16 13:13:30 浏览: 65
可以使用一个布尔型的数组来记录每个字符是否出现过,如果出现过就将其删除。具体实现如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char s[101];
scanf("%s", s);
int len = strlen(s);
int appeared[256] = {0}; // 初始化为0
int i, j;
for (i = 0, j = 0; j < len; j++) {
if (!appeared[s[j]]) { // 如果字符没出现过
s[i++] = s[j]; // 将其加入结果串中
appeared[s[j]] = 1; // 标记为出现过
}
}
s[i] = '\0'; // 结束字符串
printf("%s\n", s);
return 0;
}
```
这里使用了一个 appeared 数组来记录每个字符是否出现过。具体实现中,我们从头到尾遍历字符串,如果当前字符没有出现过,就将其加入结果串中,并将其标记为出现过。如果当前字符已经出现过,就不做任何操作,直接跳过。遍历完成后,将结果串以'\0'结尾并输出即可。
相关问题
用c语言输入5个长度不超过100的字符串,输出其中最长的字符串及其长度
可以使用一个循环来输入5个字符串,同时记录每个字符串的长度,然后再找到最长的字符串并输出其长度和内容。
以下是使用C语言实现的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[5][101]; // 存储5个字符串,每个字符串长度不超过100
int len[5]; // 存储5个字符串的长度
int max_len = 0; // 最长字符串的长度
int max_index = 0; // 最长字符串的下标
// 循环输入5个字符串,并记录每个字符串的长度
for (int i = 0; i < 5; i++) {
printf("请输入第%d个字符串:", i+1);
scanf("%s", str[i]);
len[i] = strlen(str[i]);
}
// 找到最长的字符串
for (int i = 0; i < 5; i++) {
if (len[i] > max_len) {
max_len = len[i];
max_index = i;
}
}
// 输出最长的字符串及其长度
printf("最长的字符串为:%s\n", str[max_index]);
printf("长度为:%d\n", max_len);
return 0;
}
```
注意,上述代码中使用了C语言标准库的`strlen()`函数来获取字符串长度,需要在程序开头添加`#include <string.h>`头文件。另外,为了避免输入字符串超过数组长度导致的缓冲区溢出,我们限制了每个字符串的长度不超过100。
用c语言求一个长度不超过30的字符串中数字的个数
可以使用C语言中的isdigit函数判断字符是否是数字,然后遍历字符串,统计出数字的个数即可。代码示例如下:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[31];
int count = 0;
printf("请输入一个长度不超过30的字符串:");
scanf("%s", str);
for(int i = 0; str[i] != '\0'; i++) {
if(isdigit(str[i])) {
count++;
}
}
printf("该字符串中数字的个数为:%d\n", count);
return 0;
}
```
输入一个字符串,例如 "abc123def456",输出结果如下:
```
请输入一个长度不超过30的字符串:abc123def456
该字符串中数字的个数为:6
```
相关推荐
![](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)