1) 定义一个函数,查找指定字符在字符串中出现的次数。 2) 在main函数中输入一个字符串以及要查找的字符,调用上述函数,并输出结果。 例如输入字符串 "I am a teacher",输入查找的字符 'a',输出结果:a出现的次数是3。
时间: 2024-02-25 09:58:59 浏览: 24
可以使用以下的代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
int countChar(string str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == c) {
count++;
}
}
return count;
}
int main() {
string str;
char c;
cout << "请输入一个字符串:";
getline(cin, str);
cout << "请输入要查找的字符:";
cin >> c;
int count = countChar(str, c);
cout << c << "出现的次数是" << count << endl;
return 0;
}
```
这个程序首先定义了一个函数`countChar`,该函数接受两个参数:一个字符串和一个字符,返回指定字符在字符串中出现的次数。函数遍历字符串中的每个字符,如果遇到指定字符,则将计数器加1。最后返回计数器的值。
在`main`函数中,程序首先读取输入的字符串和要查找的字符,然后调用`countChar`函数,并将返回值存储在`count`变量中。最后程序输出指定字符出现的次数。
相关问题
写一函数,求一个字符串的长度,在main函数中输入字符串
题目:写一个函数,求一个字符串的长度,在main函数中输入字符串。
答案:
在main函数中先输入一个字符串,然后调用计算字符串长度的函数,输出结果即可。
示例代码:
```
#include <stdio.h>
#include <string.h>
int str_len(char *s)
{
int len = 0;
while(*s++) {
len++;
}
return len;
}
int main()
{
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = str_len(str);
printf("字符串%s的长度为:%d\n", str, len);
return 0;
}
```
输出示例:
```
请输入一个字符串:hello, world!
字符串hello,的长度为:6
```
写一个函数,求一个字符串的长度,在main函数中输入字符串
以下是一个求字符串长度的函数:
```c++
#include <iostream>
#include <string>
using namespace std;
int getLength(string str) {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}
int main() {
string str;
cout << "请输入一个字符串:";
cin >> str;
int len = getLength(str);
cout << "字符串长度为:" << len << endl;
return 0;
}
```
该函数使用了一个 while 循环来遍历字符串,每次遍历都将长度加 1,直到遇到字符串的结束符 `\0`。在 main 函数中,先输入一个字符串,然后调用 getLength 函数来求出字符串的长度,并输出结果。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.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)