如何从两个单词之间返回一个字符串?例如:
hello how are you doing today?
输出结果为:
diff
我一直很好奇我将如何做到这一点。
答案 0 :(得分:0)
您可以使用std::string::substr
假设您分别知道"START"
和"STOP"
的长度为5
和4
,
你可以这样做:
std::string str = "STARThello how are you doing today?END";
const int startSize = 5; //or perharps something like startString.size()
const int endSize = 4; //or perharps something like stopString.size()
const int countSize = str.size() - (startSize + endSize);
std::string substring = str.substr(startSize, countSize);
答案 1 :(得分:0)
对于std :: regex来说可能是个好例子,它是C ++ 11的一部分。
#include <iostream>
#include <string>
#include <regex>
int main()
{
using namespace std::string_literals;
auto start = "START"s;
auto end = "END"s;
std::regex base_regex(start + "(.*)" + end);
auto example = "STARThello how are you doing today?END"s;
std::smatch base_match;
std::string matched;
if (std::regex_match(example, base_match, base_regex)) {
// The first sub_match is the whole string; the next
// sub_match is the first parenthesized expression.
if (base_match.size() == 2) {
matched = base_match[1].str();
}
}
std::cout << "example: \""<<example << "\"\n";
std::cout << "matched: \""<<matched << "\"\n";
}
打印:
example: "STARThello how are you doing today?END"
matched: "hello how are you doing today?"
我所做的是创建一个程序,创建两个字符串,start
和end
,用作我的开始和结束匹配。然后我使用正则表达式字符串来查找它们,并匹配中间的任何内容(包括任何内容)。然后我使用regex_match查找表达式的匹配部分,并将匹配设置为匹配的字符串。
有关详细信息,请参阅 http://en.cppreference.com/w/cpp/regex 和 http://en.cppreference.com/w/cpp/regex/regex_search