Skip to content

Instantly share code, notes, and snippets.

@petitchamp
Last active October 13, 2022 17:38
Show Gist options
  • Save petitchamp/b61f42d509f0c4466b626ad505d0497d to your computer and use it in GitHub Desktop.
Save petitchamp/b61f42d509f0c4466b626ad505d0497d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
void FindWord(string &TargetWord, string &Phrase)
{
cout << "Find: " << TargetWord << " in: \""<< Phrase<<"\"" << endl;
std::transform(Phrase.begin(), Phrase.end(), Phrase.begin(), [](unsigned char c){ return std::tolower(c); });
std::transform(TargetWord.begin(), TargetWord.end(), TargetWord.begin(), [](unsigned char c){ return std::tolower(c); });
//cout << "lower phrase: " << Phrase << endl;
//cout << "lower TargetWord: " << TargetWord << endl;
string Space = " ";
int Count = 0;
int FirstPosition = -1;
auto SpacePosition = 0;
auto NextSpacePosition = Phrase.find(Space);
while (SpacePosition < Phrase.length())
{
// test string begins with Space
if (SpacePosition == NextSpacePosition)
{
cout << "continue" << endl;
NextSpacePosition = Phrase.find(Space, ++SpacePosition);
}
string Word = Phrase.substr(SpacePosition, NextSpacePosition-SpacePosition);
//cout<< Word<< endl;
// 找到目标单词就计数
if (TargetWord.compare(Word) == 0)
{
if(Count == 0 ){
FirstPosition = SpacePosition;
}
Count ++;
}
//找下一个空格位置
SpacePosition = NextSpacePosition + Space.length();
NextSpacePosition = Phrase.find(Space, SpacePosition);
// 如果不是以空格结尾,也要把最后一个单词取出来
if(NextSpacePosition == std::string::npos )
{
NextSpacePosition = Phrase.length();
}
}
// 输出结果
if(Count)
{
std::cout << "Count: " << Count << std::endl;
std::cout << "FirstPosition: "<<FirstPosition+1 << std::endl;
}
else
std::cout << "FirstPosition: "<<FirstPosition << std::endl;
}
int main()
{
//创建测试例子
std::vector<string> PhraseList, TargetWordList;
TargetWordList.push_back(string("tst"));
PhraseList.push_back(string("Tst test TsT"));
TargetWordList.push_back(string("Do"));
PhraseList.push_back(string("Just do it"));
TargetWordList.push_back(string("2"));
PhraseList.push_back(string("1 5"));
//getline(cin, Phrase);
//getline(cin, TargetWord);
for(int ii =0 ; ii < PhraseList.size();ii++)
{
FindWord(TargetWordList[ii], PhraseList[ii]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment