[英]Function to find and replace string in char array (streams) c++
我正在尝试找到一种方法来查找在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
之后,我更喜欢使用字符数组
以下是很容易遵循: -
#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;
}
你需要两个 for循环,一个在另一个里面。 外部for循环一次通过Memory
字符串一个字符。 内部循环开始在外部循环中查找您所在位置的FindWord
。
这是一个经典案例,您需要将问题分解为更小的步骤。 您正在尝试的可能有点过于复杂,无法一次性完成。
请尝试以下策略
1)编写一些代码来查找另一个字符串中给定位置的字符串,这将是内部循环。
2)将步骤1中的代码放在另一个循环(外循环)中,该循环遍历您正在搜索的字符串中的每个位置。
3)现在您可以在另一个字符串中找到所有出现的字符串,添加替换逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.