【问题标题】:c++ how to replace a string in an array for another stringc ++如何将数组中的字符串替换为另一个字符串
【发布时间】:2017-09-07 15:00:47
【问题描述】:

我正在尝试一个使用数组的短代码,当我调用我的函数 WordReplace 时,我基本上想用恨换爱,但我一直在打印同样的东西:

我不喜欢 C++ 我不喜欢c++

我尝试了不同的方法,但我不确定哪里出了问题

#include <iostream>
#include <string>
using namespace std;

void WordReplace(string*x, int start, int end, string g, string w)
{
   for (int z = start; z <= end; z++)
   {
      if (x[z] == g)
         x[z] == w;

      cout << x[z]<<" ";
   }
}

int main()
{
   string x[4] = {"I", "don't", "hate", "c++"};

   for (int i = 0; i < 4; i++)
   {
      cout << x[i] << " ";
   }
   cout << endl;

   WordReplace(x, 0, 3, "hate", "love");

   cout << endl;

   return 0;
}

【问题讨论】:

  • x[z] == w 应该是 x[z] = w。在您最喜欢的 C++ 教科书中了解 === 之间的区别。
  • 这也可能有助于为您的变量提供更直观的名称。至少gw 不要为我这样做。但@IgorTandetnik 有你的答案。
  • 我尝试了不同的方法 -- 除了 std::replace 算法函数,它在一行代码中完成了这项工作。关键是,如果您编写的代码感觉之前必须完成数百万次(例如将 x 替换为 y),那么很可能有一个 STL 算法函数可以完成这项工作(如果不是一组函数)。
  • 实际上 gcc 5.1.0 不会产生任何警告。原因似乎是运算符重载。当std::string 替换为int 时,会按预期产生警告“statement has no effect”。
  • 尝试使用std::vector&lt;std::string&gt; 而不是数组。更容易传递给函数。

标签: c++ arrays string


【解决方案1】:

只需使用std::replace:

std::string x[] = {"I", "don't", "hate", "c++"};
std::replace( std::begin( x ), std::end( x ), "hate", "love" );

live example

【讨论】:

    【解决方案2】:

    你有 C++。使用适当的容器(例如 std::vector)。

    #include <string>
    #include <vector>
    #include <iostream>
    using namespace std;
    
    void WordReplace(vector<string> &sentence, string search_string,
                 string replace_string) {
        for (auto &word : sentence) {
            if (word == search_string)
                word = replace_string;
        }
    }
    
    int main() {
        vector<string> sentence{"I", "don't", "hate", "c++"};
    
        for (const auto word : sentence)
            cout << word << " ";
        cout << endl;
    
        WordReplace(sentence, "hate", "love");
    
        for (const auto word : sentence)
            cout << word << " ";
        cout << endl;
    
         return 0;
    }
    

    甚至更好,不要重新发明轮子

    std::vector<std::string> x {"I", "don't", "hate", "c++"};
    std::replace( x.begin(), x.end(), "hate", "love" );
    

    【讨论】:

      【解决方案3】:

      如果你想给一个变量分配一个新值,你需要下面的语法:

      myVar = myValue;
      

      这会将 myVar 的值更改为 myValue。

      这个结构:

      myVar == myValue
      

      是一个比较并被视为布尔值,因为它返回 true(如果 myVar 等于 myValue)和 False(如果它们不相等)。该构造不会更改 myVar 或 myValue 的值。

      根据 Igor 的建议,您需要将 x[z] == w 替换为 x[z] = w

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 2012-07-16
        • 2014-05-31
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        相关资源
        最近更新 更多