【问题标题】:Function to find and replace string in char array (streams) c++在char数组(流)c ++中查找和替换字符串的函数
【发布时间】:2013-08-26 05:39:09
【问题描述】:

我正在尝试找到一种方法来搜索 char 数组中的字符串,然后在每次出现时将其替换为另一个字符串。我很清楚该怎么做,但流背后的整个语法有时会让我感到困惑。无论如何,到目前为止我的代码(而且不是很多)是:

string FindWord = "the";
string ReplaceWord = "can";

int i = 0;
int SizeWord = FindWord.length();
int SizeReplace = ReplaceWord.length();

while (   Memory[i] != '\0')
{
         //now i know I can probably use a for loop and 
         //then if and else statements but im just not quite sure
    i++; //and then increment my position
}

我通常不会这么慢:/有什么想法吗?

【问题讨论】:

  • 我认为您的意思是字符串而不是流。流完全是另一回事。
  • 嗯,是的,我猜是这样,稍后我将在程序中将数组读取到流中。
  • 你能把目标也改成std::string吗?

标签: c++ arrays stream


【解决方案1】:

在将字符数组转换为 std::string 后,我更喜欢玩弄它

跟随很简单:-

#include<iostream>
#include<string>

int main ()
{

char memory[ ] = "This is the char array"; 
 //{'O','r',' ','m','a','y',' ','b','e',' ','t','h','i','s','\0'};

std::string s(memory);

std::string FindWord = "the";
std::string ReplaceWord = "can";


std::size_t index;
    while ((index = s.find(FindWord)) != std::string::npos)
        s.replace(index, FindWord.length(), ReplaceWord);

std::cout<<s;
return 0;
}

【讨论】:

  • 对不起,我不熟悉语法 std::string,这是什么意思?
  • @newprogramer std 命名空间。 :: 运算符是 scope 运算符。它告诉编译器在哪个类/命名空间中查找标识符。 string 是命名空间 std 中的一个类。我建议你在 C++ 上从一个好的初学者 book 开始
  • 那 size_t 索引部分呢?
【解决方案2】:

你需要 两个 for 循环,一个在另一个里面。外部 for 循环一次遍历一个字符的 Memory 字符串。内层循环开始在外层循环的位置寻找FindWord

这是一个经典案例,您需要将问题分解为更小的步骤。您正在尝试的可能有点过于复杂,您无法一口气完成。

尝试以下策略

1) 编写一些代码find一个字符串在另一个字符串的给定位置,这将是内部循环。

2) 将步骤 1 中的代码放入另一个循环(外循环)中,该循环遍历您正在搜索的字符串中的每个位置。

3) 现在您可以查找一个字符串在另一个字符串中的所有出现,添加替换逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 2021-12-11
    • 2016-02-09
    • 2012-06-06
    相关资源
    最近更新 更多