从两个单词之间获取字符串

Getting a string from in between two words?

本文关键字:单词 之间 获取 字符串 两个      更新时间:2023-10-16

如何从两个单词之间返回字符串?例如:

STARThello how are you doing today?END

输出为:

hello how are you doing today?

我一直很好奇我该怎么做。

对于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?"

我所做的是创建一个程序,创建两个字符串startend,作为我的开始和结束匹配项。然后,我使用一个正则表达式字符串来查找它们,并与它们之间的任何内容(不包括任何内容)进行匹配。然后我使用regex_match来查找表达式的匹配部分,并将match设置为匹配字符串。

有关更多信息,请参阅http://en.cppreference.com/w/cpp/regex和http://en.cppreference.com/w/cpp/regex/regex_search

您可以使用std::string::substr

假设您知道"START""STOP"的长度分别为54

你可以这样做:

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);