2014-05-22 93 views
0

在我现在正在处理的代码中,我有一个向量从txt文件加载,现在我试图查看它们是否可以替换矢量中某些单词而不需要位置或任何
因此,例如,如果TXT含有动物名单,我想换鸟的书怎么会怎么做,如果没有需要的字母位置替换矢量中的字符串而没有定位

#include <iostream> 
#include <string> 
#include <vector> 
#include <fstream> 

using namespace std; 

vector <string> test; 

int main() 
{ 
    string file; 
    fstream fout("Vector.txt"); 
    while (!fout.eof()) 
    { 
    getline(fout,file); 
    test.push_back(file); 
    } 
    fout.close(); 


    for(int i = 0; i < test.size(); i++) 
    { 
    cout << test[i] << endl; 
    } 


    system("pause"); 
} 

TXT包含:




河马

+0

目前还不清楚是什么你在测试[I](一个词,一个句子?)。 – Kiroxas

+0

可能重复的[尝试替换字符串中的单词](http://stackoverflow.com/questions/9053687/trying-to-replace-words-in-a-string) –

+0

可以发布一个输入txt示例和一个可能产出预期?我无法理解你想要做什么。 – hidrargyro

回答

0

试试这个:

typedef std::istream_iterator<string> isitr; 

ifstream fin("Vector.txt"); 
vector <string> test{ isitr{fin}, isitr{} }; // vector contains strings 

map<string,string> dict{ // replacements dictionary 
    {"bird", "book"}, {"cat", "kitten"} 
}; 

for(auto& x: test) // x must be a reference 
{ 
    auto itr = dict.find(x); 
    if(itr != dict.end()) // if a match was found 
     x = itr->second; // replace x with the found replacement 
         // (this is why x must be a reference) 
} 

for(const auto& x: test) 
    cout << test << " "; 
2

使用std::transform()

std::string bird2book(const string &str) 
{ 
    if (str == "bird") 
     return "book"; 
    return str; 
} 

std::transform(test.begin(), test.end(), test.begin(), bird2book); 
1

可以使用std::replace

std::replace (test.begin(), test.end(), "bird", "book"); 
0

使用STL!这是我们的力量。你需要的一切:

#include <iostream> 
#include <algorithm> 
#include <iterator> 
#include <vector> 
#include <string> 
#include <fstream> 
#include <map> 

int main() 
{ 
    std::vector<std::string> words; 

    const std::map<std::string, std::string> words_to_replace{ 
      { "bird", "book" }, { "cat", "table" } 
     }; 
    auto end = words_to_replace.cend(); 

    std::transform(
     std::istream_iterator<std::string>{ std::ifstream{ "file.txt" } }, 
     std::istream_iterator<std::string>(), 
     std::back_inserter(words), 
     [&](const std::string& word) { 
      auto word_pos = words_to_replace.find(word); 
      return (word_pos != end) ? word_pos->second : word; 
     }); 

    std::copy(words.cbegin(), words.cend(), 
     std::ostream_iterator<std::string>(std::cout, "\n")); 
    std::cout << std::endl; 
}