编写STL程序,给定两个二进制字符串A和B,编写函数返回字符串A在字符串B中所出现的次数
时间: 2024-03-14 07:43:53 浏览: 17
以下是使用STL的C++代码实现:
```c++
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string A = "10101";
std::string B = "11010101101";
int count = 0;
std::string::size_type pos = 0;
while ((pos = B.find(A, pos)) != std::string::npos) {
count++;
pos += A.length();
}
std::cout << "A occurs in B " << count << " times" << std::endl;
return 0;
}
```
我们可以使用`std::string`的`find()`函数来查找字符串A在B中出现的位置。由于`find()`函数返回的是字符串的位置,我们可以利用这个位置来查找下一个出现的位置,直到`find()`函数返回`std::string::npos`表示字符串A在B中不存在。
在循环中,我们使用变量`pos`来记录当前查找的位置。每次找到字符串A后,我们将计数器加1,然后将`pos`移动到下一个查找的位置。
最后,我们输出计数器的值,即字符串A在B中出现的次数。
相关问题
编写STL程序,自行设计split()函数,要求输入一个字符串和一个分隔符,返回一个字符串向量作为分割结果
好的,下面是一个简单的实现:
```c++
#include <iostream>
#include <string>
#include <vector>
// split函数,将str按照delim分隔符进行分割
std::vector<std::string> split(const std::string& str, const char delim)
{
std::vector<std::string> result;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delim))
{
result.push_back(token);
}
return result;
}
int main()
{
std::string input = "Hello World,How are you today?";
char delim = ',';
std::vector<std::string> result = split(input, delim);
for (const auto& s : result)
{
std::cout << s << std::endl;
}
return 0;
}
```
上述程序中,我们使用了 `std::istringstream` 类型的 `tokenStream` 对象,将输入字符串 `str` 进行分割,分隔符为 `delim`。`std::getline` 函数用于从 `tokenStream` 中获取每个子串,并将其存储到 `result` 向量中。最后,我们输出了分割结果。
C++ 统计vector<string>a容器中某个字符串出现的次数
可以使用STL中的`count`函数来统计某个字符串在vector中出现的次数。示例如下:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> a = {"hello", "world", "hello", "world", "welcome", "hello"};
std::string target = "hello";
int count = std::count(a.begin(), a.end(), target);
std::cout << "The count of " << target << " is " << count << std::endl;
return 0;
}
```
输出结果为:
```
The count of hello is 3
```
其中,`count`函数的第一个参数是容器的起始迭代器,第二个参数是容器的结束迭代器,第三个参数是要统计的字符串。`count`函数返回的是统计结果。