Question

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;
}
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top