简体   繁体   English

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

[英]Function to find and replace string in char array (streams) c++

I'm trying to find a way to find a way to search for a string in a char array then replace it with another string every time it occurs. 我正在尝试找到一种方法来查找在char数组中搜索字符串的方法,然后在每次发生时将其替换为另一个字符串。 I have a fair idea of what to do but the whole syntax behind streams sometimes confuses me. 我对如何做有一个很好的想法,但流后面的整个语法有时会让我感到困惑。 Anyway my code so far (and it isnt very much) is: 无论如何我的代码到目前为止(并且它不是很多)是:

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
}

Im not usually this slow :/ any ideas? 我通常不会这么慢:/任何想法?

I'd prefer to play around with character array after converting it to std::string 在将其转换为std::string之后,我更喜欢使用字符数组

Following is simple to follow :- 以下是很容易遵循: -

#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;
}

You need two for loops, one inside the other. 你需要两个 for循环,一个在另一个里面。 The outer for loop goes through the Memory string one character at a time. 外部for循环一次通过Memory字符串一个字符。 The inner loop starts looking for the FindWord at the position you've got to in the outer loop. 内部循环开始在外部循环中查找您所在位置的FindWord

This is a classic case where you need to break the problem down into smaller steps. 这是一个经典案例,您需要将问题分解为更小的步骤。 What you are trying is probably a bit too complex for you to do in one go. 您正在尝试的可能有点过于复杂,无法一次性完成。

Try the following strategy 请尝试以下策略

1) Write some code to find a string at a given position in another string, this will be the inner loop. 1)编写一些代码来查找另一个字符串中给定位置的字符串,这将是内部循环。

2) Put the code in step 1 in another loop (the outer loop) that goes through each position in the string you are searching in. 2)将步骤1中的代码放在另一个循环(外循环)中,该循环遍历您正在搜索的字符串中的每个位置。

3) Now you can find all occurrences of one string in another, add the replace logic. 3)现在您可以在另一个字符串中找到所有出现的字符串,添加替换逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM