用于在char数组(流)c ++中查找和替换字符串的函数

问题描述 投票:1回答:2

我正在尝试寻找一种方法来搜索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
}

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

c++ arrays stream
2个回答
3
投票

我希望将其转换为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;
}

0
投票

您需要two

© www.soinside.com 2019 - 2024. All rights reserved.