我只想在字串中查找模式。例如,對于這個“abaxavabaabcabbc”字串,應用程式應該列印“abc”和“abbc”。所以,模式應該有“abc”,但“b”的數字正在改變。模式 => "abc" => "b" 的數字是可變的。并且程式應該是C 。
uj5u.com熱心網友回復:
使用 regex_search 而不是迭代器:
住在 Coliru
#include <regex>
#include <string>
#include <iostream>
int main() {
std::regex const pattern("ab c");
for (std::string const text :
{
"abaxavabaabcabbc",
}) //
{
std::smatch match;
for (auto it = text.cbegin(), e = text.cend();
std::regex_search(it, e, match, pattern); it = match[0].second) {
std::cout << "Match: " << match.str() << "\n";
}
}
}
印刷
Match: abc
Match: abbc
uj5u.com熱心網友回復:
這個問題只有一個答案。您必須使用std::regex. 正則運算式正是為此目的而制作的。
C 也支持正則運算式。請看這里
正則運算式“ab c”將匹配所有以“a”開頭、具有一個或多個“b”并以“c”結尾的字串
請參閱以下非常簡短的程式:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <regex>
const std::regex re{ R"(ab c)" };
using Iter = std::sregex_token_iterator;
int main() {
const std::string test{ "abaxavabaabcabbc" };
std::copy(Iter(test.begin(), test.end(), re), Iter(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
該程式將遍歷所有匹配的模式并將它們復制到 std::cout
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/353920.html
上一篇:基于圖堆的優先佇列實作
下一篇:C#SPOJ時間優化
