1

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?

cpp
  • 3,743
  • 3
  • 24
  • 38
newprogramer
  • 39
  • 2
  • 6

2 Answers2

3

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;
}
P0W
  • 46,614
  • 9
  • 72
  • 119
  • im sorry im not familiar with the syntax std::string, what does that mean? – newprogramer Aug 27 '13 at 04:25
  • @newprogramer `std` a namespace. The `::` operator is the `scope` operator. It tells the compiler which class/namespace to look in for an identifier. `string` is a class in namespace `std`. I suggest you to get started with a good beginner [book](http://stackoverflow.com/q/388242/1870232) on C++ – P0W Aug 27 '13 at 05:17
  • and what about that size_t index portion? – newprogramer Aug 27 '13 at 06:32
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.

john
  • 85,011
  • 4
  • 57
  • 81