匹配一个单词的模式并提取整个单词
Match a word for pattern and extracting the whole word
我正在尝试编写一个函数,该函数将单个单词的一部分与输入的文本相匹配,并在该单词中存在该模式的情况下打印整个单词。我正在使用c++。请帮忙。下面是我尝试使用字符串函数编写的一个函数,但有了这个函数,我只能知道一个单词是否存在于句子中。但我需要提取一个单词,它的部分与输入的文本相匹配。我希望我的问题很清楚。
#include <cctype>
#include <iostream>
#include <string>
bool contains_word(const std::string& sentence, const std::string& word)
{
size_t pos = 0;
// Find the start of 'word' in 'sentence'.
while ((pos = sentence.substr(pos).find(word)) != std::string::npos) {
if (!(isalpha(sentence[pos - 1])) || !(isalpha(sentence[pos + word.size() +1])))
return true;
}
return false;
}
std::string get_word(const std::string& sentence, const std::string& substr)
{
std::string::size_type it = sentence.find(substr);
if(it == std::string::npos)
return "";
std::string::size_type it2 = it;
for(; it >= 1 && !std::isspace(sentence[it - 1]); --it);
for(; it2 <= sentence.size() - 1 && !std::isspace(sentence[it2 + 1]); ++it2);
return sentence.substr(it, (it2 + 1) - it);
}
int main()
{
std::string str("kchmviewer gnome-terminal");
std::cout << get_word(str, "viewer") << std::endl;
std::cout << get_word(str, "terminal") <<std::endl;
return 0;
}
输出为:
kchmviewer
gnome-terminal
相关文章:
- 文本文件中的单词链表
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在指针的帮助下,文本文件中单词的频率
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 如何根据单词在文本中出现的概率输出单词
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 使用可变模板的Broadcaster/Listener模式
- c++方法参数只能在linux的发布模式下自行更改
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 搜索单词时的字母模式逻辑
- 在字典中查找单词模式,高性能
- 匹配嵌入模式的单词
- 匹配一个单词的模式并提取整个单词