在矢量中替换字符串而不定位

replacing a string in a vector without positioning

本文关键字:定位 字符串 替换      更新时间:2023-10-16

在我正在编写的代码中,我现在有一个从txt文件加载的矢量,现在我想看看它们是否可以替换矢量中的某些单词,而不需要位置或任何东西
例如,如果TXT包含一个动物列表而我想将bird更改为book在不需要

字母位置的情况下如何做到这一点呢?
#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包含:


狗猫

河马

使用std::transform()

std::string bird2book(const string &str)
{
    if (str == "bird")
        return "book";
    return str;
}
std::transform(test.begin(), test.end(), test.begin(), bird2book);

您可以使用std::replace

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

试试这个:

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 << " ";

使用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;
}