在字符串中查找一对字符

Finding a Pair of character in a string

本文关键字:字符 查找 字符串      更新时间:2023-10-16
#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 搜索(请参阅字符串搜索算法(来使您的解决方案更加复杂,并在找到每次出现后将其恢复到正确的状态。