编写一个程序,输入一个字符串str(长度不超过30)和一个字符ch通过指针查找、统计字符串str中字符ch出现的位置(区分大小写)。【输入形式】输入一个字符串str,以及一个字符ch
时间: 2024-06-09 20:09:37 浏览: 12
下面是一个简单的 C 语言程序,实现了输入字符串和字符,然后查找并统计字符在字符串中出现的位置:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[31], ch;
printf("请输入一个字符串(长度不超过30):");
scanf("%s", str);
printf("请输入一个字符:");
scanf(" %c", &ch); // 注意需要加一个空格,避免读取上一次输入的回车符
int count = 0;
printf("字符 %c 在字符串中出现的位置:", ch);
for (int i = 0; i < strlen(str); i++) {
if (str[i] == ch) {
printf("%d ", i);
count++;
}
}
printf("\n字符 %c 在字符串中共出现了 %d 次。\n", ch, count);
return 0;
}
```
程序首先提示用户输入一个字符串和一个字符,然后通过 `scanf()` 函数分别读取输入。接下来,程序用一个循环遍历字符串中的每个字符,检查是否与目标字符相同,如果相同则打印出该字符在字符串中的位置,并计数器加一。最后,程序输出字符在字符串中出现的次数。注意字符串长度不能超过 30,否则可能会出现缓冲区溢出的问题。
相关问题
编写一个程序,输入一个字符串str和一个字符ch,通过指针查找,统计字符串str中ch出现的位置
下面是一个 C++ 的程序实现:
```c++
#include <iostream>
using namespace std;
void findChar(char* str, char ch) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == ch) {
count++;
cout << "字符" << ch << "出现在第" << i+1 << "个位置" << endl;
}
}
if (count == 0) {
cout << "字符" << ch << "在字符串中未出现" << endl;
}
}
int main() {
char str[100], ch;
cout << "请输入一个字符串:";
cin.getline(str, 100);
cout << "请输入一个字符:";
cin >> ch;
findChar(str, ch);
return 0;
}
```
程序首先输入一个字符串和一个字符,然后通过指针遍历字符串,统计字符出现的次数并输出其位置。如果字符在字符串中未出现,则输出提示信息。
编写一个程序,输入一个字符串str和一个字符ch,通过指针查找,统计字符串str中字符ch出现的位置
下面是一个示例程序,实现了输入一个字符串和一个字符,然后通过指针查找,统计字符串中字符出现的位置:
```c
#include <stdio.h>
#include <string.h>
void find_char(const char *str, char ch);
int main()
{
char str[100], ch;
printf("请输入字符串:");
gets(str);
printf("请输入要查找的字符:");
scanf("%c", &ch);
find_char(str, ch);
return 0;
}
void find_char(const char *str, char ch)
{
int count = 0;
const char *p = str;
while (*p)
{
if (*p == ch)
{
printf("%d ", p - str);
count++;
}
p++;
}
if (count == 0)
{
printf("未找到该字符");
}
else
{
printf("\n共找到%d个字符", count);
}
}
```
运行程序后,输入一个字符串和一个字符,程序会输出该字符在字符串中出现的位置,如果没有找到该字符,则输出提示信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)