用C++ 写一个函数,参数为string类型,一个string1,一个string2,返回string1中string2的个数
时间: 2024-05-01 08:17:44 浏览: 13
好的,我会回答你的问题。以下是一个用 C 语言写的函数,可以计算一个字符串中另一个字符串的个数:
```c
#include<stdio.h>
#include<string.h>
int countSubstring(char *string1, char *string2) {
int count = 0;
char *pos = string1;
while ((pos = strstr(pos, string2)) != NULL) {
count++;
pos += strlen(string2);
}
return count;
}
```
这个函数的实现很简单,它通过循环遍历 string1 中的每一个子串,检查是否与 string2 匹配,如果匹配成功就计数器加一,继续检查下一个子串。最后返回匹配的总数。
你可以把这个函数复制到你的项目中并调用它,传入 string1 和 string2 两个参数即可。希望对你有帮助!
相关问题
用C++ 写一个函数,参数有一个String类型,一个Char类型,返回String中Char的个数
好的,您可以使用以下代码实现:
```c
int countCharInString(char *str, char c) {
int count = 0;
while (*str) {
if (*str == c) {
count++;
}
str++;
}
return count;
}
```
使用方法如下:
```c
char *str = "hello world";
char c = 'o';
int count = countCharInString(str, c);
printf("%d", count); // 输出 2
```
希望能够帮到您!
C++如何获取一个string的大小
在C++中,可以使用`std::string`的`size()`成员函数来获取一个字符串的大小,即字符的个数。以下是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::cout << "字符串的大小为:" << str.size() << std::endl;
return 0;
}
```
在上述示例中,我们创建了一个名为`str`的`std::string`对象,并初始化为"Hello, World!"。然后,我们使用`size()`函数获取字符串的大小,并将结果输出到控制台。在这个例子中,字符串的大小为13(包括空格和标点符号)。你可以通过调用`size()`函数来获取任何`std::string`对象的大小。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)