1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
#include <string>
#include <vector>
#include <utility>
using pos_string = std::pair<int,std::string>;
std::vector<pos_string> tokenize(const std::string& data,const std::string& delim = " "); //split words in a sentence
std::vector<pos_string> get_all_matches(const std::string& data,const std::string& phrase); //match all words that end with phrase
bool ends_with(const std::string& word,const std::string& phrase);///check if word ends with phrase
int main()
{
std::string input{},phrase{};
std::cout<<"Enter your string: ";
std::getline(std::cin,input,'\n');
std::cout<<"Enter your search string: ";
std::cin>>phrase;
std::cout<<"\n\n";
auto vec(get_all_matches(input,phrase));
for(auto ind_wrd : vec)
{
std::cout<<"Index: "<<ind_wrd.first<<" Word: "<<ind_wrd.second<<std::endl;
}
}
std::vector<pos_string> tokenize(const std::string& data,const std::string& delim)
{
std::vector<pos_string> result{};
std::size_t delim_pos=0,index=0;
while((delim_pos = data.find(delim,delim_pos)) != std::string::npos)
{
std::string temp(data.begin()+index,data.begin()+delim_pos);
result.push_back(std::make_pair(index,temp));
index = data.find_first_not_of(delim,delim_pos);
delim_pos = index;
}
result.push_back(std::make_pair(index,std::string(data.begin()+index,data.end())));
return result;
}
std::vector<pos_string> get_all_matches(const std::string& data,const std::string& phrase)
{
std::vector<pos_string> _tokens(tokenize(data));
std::vector<pos_string> result{};
for(auto indx_word : _tokens)
{
if(ends_with(indx_word.second,phrase))
result.push_back(indx_word);
}
return result;
}
bool ends_with(const std::string& word,const std::string& phrase)
{
auto pos = word.rfind(phrase);
if(pos != std::string::npos && (word.substr(pos,word.size()) == phrase))
return true;
return false;
}
|