在字符串中查找一对字符
Finding a Pair of character in a string
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int count = 0;
vector<string> v;
string resp;
cin >> resp;
v.push_back(resp);
for(int i = 0; i < v.size(); i++){
if(find(v.begin(), v.end(), "xy") != v.end()){
count++;
}
cout << count << endl;
}
return 0;
}
我想在多个测试用例的字符串中找到字符"xy"。 对于输入 xy,我的计数值正确输出为 1。
但是对于输入 xyxxy 而不是 2,它给出的值为 0 它只找到一次值,但我想检查整个字符串中 xy 的计数
我也尝试使用子字符串函数,但它无法正常工作
我不明白while循环的想法,但这对我有用。
#include <iostream>
#include <vector>
int main()
{
std::string str;
std::cin >> str;
int count = 0;
for (int i(0); i < str.size()-1; ++i)
{
if ((str[i] == 'x') && (str[i + 1] == 'y'))
{
++count;
}
}
std::cout << count;
}
您正在字符串向量中查找"xy",在您的示例中,该向量具有单个元素"xyxxy"。由于"xy"不等于"xyxxy",因此找不到任何匹配项。
但即使你试图在"xyxxy"本身中std::find
"xy"——那也会失败,因为std::find
在一个范围内(或者更确切地说,迭代器对(中寻找单个元素。
相反,您可以使用string::find()
方法,如下所述;或者,视情况而定,std::string_view::find()
:
#include <string>
#include <vector>
#include <iostream>
#include <string_view>
int main() {
const std::string needle{"xy"};
std::string haystack;
std::cin >> haystack;
std::size_t count{0};
std::string_view remainder{haystack};
while(true) {
auto first_pos = remainder.find(needle);
if (first_pos == std::string_view::npos) { break; }
count++;
remainder = remainder.substr(first_pos+needle.length());
}
std::cout << "Found " << count << " occurrences of "" << needle << ""n";
}
注意:这不考虑重叠事件。如果你想要这些,你可以总是将起始位置增加 1;或者通过使用 Boyer-Moore 或 Knuth-Morris-Pratt 搜索(请参阅字符串搜索算法(来使您的解决方案更加复杂,并在找到每次出现后将其恢复到正确的状态。
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 查找字符在两个索引之间出现的次数
- 使用连续字符及其路径查找矩阵中最长路径的长度
- 在字符串中查找一对字符
- 在字符数组 (C++/根) 中查找双精度值
- C++ char 类查找字符索引
- 拆分字符串输入并查找字符是否有效
- 查找和比较两个字符串中的字符
- 从输入 1 查找输入 2 中字符的位置
- 查找单个字符串中重复次数最多和次数第二多的字符
- 如何查找两个字符串 c++ 中常用字符的数量
- 视觉C++查找以 "ing" 结尾且少于或等于 10 个字符的单词
- 如何从链表指针字符中查找字符
- 查找字符串中存在的不同字符
- LPCWSTR 查找和替换为转义字符
- 在C 中查找非空格字符
- 使用哈希 C++ 查找具有 k 个不同/唯一字符的最长子字符串
- 查找字符数组中的数字总和
- 提升正则表达式 cpp 用于查找 %% 之间的字符串,输出不包括 % 字符本身
- 查找并列出字符串C++中的所有字符簇