我想弄清楚如何在字串中找到非重疊子串的數量,但只有那些距離相同的子串。我設法獲得了非重疊子串的數量,但這只是要求的子集。
示例:我有一個字串“aaaaaaaaaabaaaaaaba”,我想計算非重疊子字串“aa”的數量,但只計算距離乘以 2 的子字串的數量。
標準的非重疊代碼回傳 8,這是正確的(aa aa aa aa aa b aa aa aa ba - 通過空格區分結果)。它找到位置 0、2、4、6、8、11、13、15 處的子串。
當我嘗試實作距離要求時,我遇到了問題。所需的計數應為 7,省略位置 11 處的“a”并在位置 12 處繼續(aa aa aa aa aa ba aa aa ab a)...再次通過空格區分結果,位置 11 處的“a”應該在位置 10 與 'b' 形成子字串 'ba'
我嘗試使用模數來識別正確的位置并只計算從模數結果 0 開始的子字串,但是通過執行我的代碼,處理只在第 5 次出現時停止,在中間的 'b' 之前,并忽略下一個。
wrong: aa aa aa aa aa b aa aa aa b a
good: aa aa aa aa aa ba aa aa ab a
同樣,它應該適用于其他大小,例如,找到“aaa”,因此結果將是 4“aaa aaa aaa aba aaa aab a”而不是 5“aaa aaa aaa ab aaa aaa ba”
string str = "aaaaaaaaaabaaaaaaba";
string sub = "aa";
int count = 0;
for (size_t offset = str.find(sub); offset != std::string::npos;
offset = str.find(sub, offset sub.length()))
{
int pos = offset % sub.length();
if (pos == 0)
{
count;
cout << "offset: " << offset << " count: " << count << endl;
}
}
cout << "count: " << count << endl;
return 0;
uj5u.com熱心網友回復:
你的回圈做錯了:它試圖find從最后找到的偏移量 2(的長度aa)開始子串。
在aa奇數位置找到第一個之后,所有后續嘗試也將找到奇數位置。
這有效:
for (size_t offset = str.find(sub); offset != std::string::npos;
offset = str.find(sub, offset 1))
uj5u.com熱心網友回復:
我建議只使用std::string::find來查找第一個子字串,然后sub.size()每次迭代都執行。
這是std::string_view在當前子字串上使用 a 的示例str:
#include <string>
#include <string_view>
#include <iostream>
int main() {
std::string str = "aaaaaaaaaabaaaaaaba";
// ! ! ! ! ! X ! ! X X
// 0 2 4 6 81012141618
std::string sub = "aa";
int count = 0;
for(size_t offset = str.find(sub);
offset < str.size() - sub.size();
offset = sub.size()) // just step sub.size() here
{
if(sub == std::string_view(str.c_str() offset, sub.size()))
std::cout << "offset: " << offset << " count: " << count << '\n';
}
std::cout << "count: " << count << '\n';
}
輸出:
offset: 0 count: 1
offset: 2 count: 2
offset: 4 count: 3
offset: 6 count: 4
offset: 8 count: 5
offset: 12 count: 6
offset: 14 count: 7
count: 7
uj5u.com熱心網友回復:
在發布我的問題幾分鐘后,我整天都試圖找到解決方案,我找到了解決方案 = 墨菲定律
訣竅是添加'else'陳述句并將偏移量移回模余數
if (pos == 0)
{
count;
cout << "offset: " << offset << " count: " << count << endl;
}
else
{
offset = offset - pos;
cout << "pos: " << pos << endl;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/346716.html
上一篇:如何在C 中打亂陣列?
