当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Match a word for pattern and extracting the whole word

问题描述:

I am trying to write a function that would match a part of a single word with an entered text and print the entire word if that pattern is present in that word . I am using c++.Please help.

Below is a function that i tried writing using string functions but with this i can only find out if a word is present in a sentence or not. But i need to extract that single word whose part matches an entered text. I hope my question is clear.

#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;
}

Output will be:

kchmviewer 
gnome-terminal
分享给朋友:
您可能感兴趣的文章:
随机阅读: