📄 words_replace.cpp
字号:
/*
* Description:
*
* Find & Replace a word in a sentence.
*
* History:
*
* Initial version created by Royal, Mar. 2004.
*
* Notes:
*
* This code has been written to conform to standard C++ and STL. It has been
* compiled successfully using GNU C++ 3.2, Borland C++ 5.5, and Visual C++ 7.0.
*/
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
using namespace std;
bool search(const vector<string>& sentence, vector<int>& pos, const string& word);
void replace(vector<string>& sentence, const vector<int>& pos, const string& word);
bool report_pos(const vector<string>& sentence, vector<int>& pos, const string& word);
void print(const vector<string>& sentence);
int main()
{
vector<string> sentence;
vector<int> pos;
string input;
cout<<"Please input a sentence:" << endl;
while(cin >> input) sentence.push_back(input);
cin.clear();
string word1;
cout<<"Please input the word you want to find:" << endl;
cin >> word1;
if (!report_pos(sentence, pos, word1)) return 1;
cout << "Please input the word you want to change to be:" << endl;
string word2;
cin >> word2;
cout << "The sentence before changed is:" << endl;
print(sentence);
replace(sentence, pos, word2);
cout << "The sentence after changed is:" << endl;
print(sentence);
return 0;
}
bool search(const vector<string>& sentence, vector<int>& pos, const string& word)
{
vector<string>::size_type size = sentence.size();
for(vector<string>::size_type i = 0; i < size; ++i)
if(sentence[i] == word) pos.push_back(i);
return !pos.empty();
}
void replace(vector<string>& sentence, const vector<int>& pos, const string& word)
{
vector<int>::size_type size = pos.size();
for(vector<int>::size_type i = 0; i < size; ++i) sentence[pos[i]] = word;
}
void print(const vector<string>& sentence)
{
vector<string>::size_type size = sentence.size();
for(vector<string>::size_type i = 0; i < size; ++i) cout << sentence[i] << " ";
cout << endl;
}
bool report_pos(const vector<string>& sentence, vector<int>& pos, const string& word)
{
if(search(sentence, pos, word))
{
cout << "Find the word at the following position: ";
vector<int>::size_type size = pos.size();
for(vector<int>::size_type i = 0; i < size; ++i) cout << setw(3) << pos[i] + 1;
cout << endl;
return true;
}
else
{
cout << "Can't find the word." << endl;
return false;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -