简体   繁体   中英

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. 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

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. The outer for loop goes through the Memory string one character at a time. The inner loop starts looking for the FindWord at the position you've got to in the outer loop.

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.

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.

3) Now you can find all occurrences of one string in another, add the replace logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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