从两个单词之间获取字符串
Getting a string from in between two words?
如何从两个单词之间返回字符串?例如:
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?"
我所做的是创建一个程序,创建两个字符串start
和end
,作为我的开始和结束匹配项。然后,我使用一个正则表达式字符串来查找它们,并与它们之间的任何内容(不包括任何内容)进行匹配。然后我使用regex_match来查找表达式的匹配部分,并将match设置为匹配字符串。
有关更多信息,请参阅http://en.cppreference.com/w/cpp/regex和http://en.cppreference.com/w/cpp/regex/regex_search
您可以使用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);
相关文章:
- 在单词之间添加空格
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- 单词之间的莫尔斯电码空格问题
- 如何读取特定单词之间的文本文件?
- 如何在两个单词之间添加空格
- 在C 中的单词之间删除除一个空间以外的所有空间
- 找出两个给定单词和字典之间最短的单词阶梯
- 从两个单词之间获取字符串
- C++均匀地分配单词之间的空格
- C++ 计算文件中两个单词之间的单词
- 使用线程在以元音或辅音开头的单词之间交替
- 删除字符串 c++ 中 < 和 > 符号之间的单词
- C++如何在两个单词之间获取字符串/字符
- 提取两个单词之间的域
- 增加单词之间的空格,按列排列单词
- C++中单词之间的常量制表位
- c ++ 如何提取单词之间的空格(如果有)
- 在文件中搜索字符串(逐行),忽略单词之间空白的大小
- 移动字符串中的单词,单词之间使用空格作为分隔符
- Wordwap函数修复保留单词之间的空白