Replacing a string in a string with another string

This is a discussion on Replacing a string in a string with another string within the C++ Programming forums, part of the General Programming Boards category; I have this problem. I have a global string, and then a function called replace that has two strings, say ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    102

    Replacing a string in a string with another string

    I have this problem. I have a global string, and then a function called replace that has two strings, say str1 and str2, as parameters. I am supposed to replace all the occurrences of str1 in the global string with str2. And I am told not to use any functions from external libraries (I don't know what this means but I think it means I shouldn't use the class string or something). I have thought about it for a long time but couldn't find a way out of it. I have thought of putting the global string in a loop, and replacing all the occurrences of str1 characters in it with str2 characters but this only allows replacement of characters, and I need to replace an entire string.

    Example:

    YetOneMoreOneTimes

    str1: One
    str2: Many.

    So our new string, after we are done with replacing it becomes:

    YetManyMoreManyTimes
    Last edited by Dontgiveup; 04-23-2011 at 05:30 PM.

  2. #2
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,859
    This is usually a pointer or array exercise. Are you studing either at the moment?

    char arrays can be used. functions like strstr() make it a simple exercise (which is why they are excluded).

    Break it down into steps.

    You will need to move through each letter (char) in the string, testing to see if it is the word we are looking for.

    This loop will increment an index (used to keep our position in the original string). This can be an 'int' or pointer (lets call it 'MainIndex') and run until the end of the original string

    Test to see if we found the 'word'

    If we found the 'word'
    add the 'new word' to output string
    increment the 'MainIndex' =+ length of 'word'
    else
    add only the single original character to output string
    increment the 'MainIndex' =+ 1

    [consider input of 'YetOhOneMoreTime']

    You need to first create a test to find the 'word' we want to replace.
    The trick is to have a new index for just the 'word' and add them to find our position in the original string.

    Code:
        
    int WordIndex = 0;
    //use both indexes in the Original string 
    while (OrigString[MainIndex + WordIndex] == Word[WordIndex] )
    {
         //match!
         //increment the WordIndex but not the MainIndex
         WordIndex++;
         //test to see if we should exit
         //if WordIndex == length of 'Word' 
              //we found the 'Word'!  
    }
    Last edited by novacain; 04-23-2011 at 10:25 PM. Reason: clarity
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    102
    Yeah you are right, we are doing pointers and character arrays, and I have already tried to do it with either or both of them but failed. Here are my questions to your suggestion (some comments (questions) inside are mine

    Code:
    int WordIndex = 0, MainIndex = 0;
    
    while (OrigString[MainIndex + WordIndex] == Word[WordIndex] )
    {
         //increment the word index if we see the first letter of the 'word '
         WordIndex++;
        
         //if WordIndex == length of 'Word' 
              //we found the 'Word'! 
              //MainIndex =+ length of 'word' //Now doesn't doing this mean our 
    //OrigString will jump 3 characters from our OrigString since by increasing 
    //WordIndex, we already were at the end of 'Word' in the OrigString
    }
    Also, doesn't this not mean that if the word is appearing more than once in the OriginString, then we will only be able to find the first word only since our condition if WordIndex == length of 'Word' will always be true after the first word. Finally, you say add the 'new word' or single original character to output string, I really don't understand how this can be done. I mean I can search through an entire string, replace any character with any other. But adding a new word or a new character to it, especially when the length of that word is different from the length of the word we want to replace it in the string, I don't know. Any help is appreciated.

  4. #4
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,859
    Each time you search for the word you will need to reset the WordIndex to zero (so it will get reset just about every character in original string).

    This can be done using the 'scope' of the variable (have you done that?) or just by reseting the variable to 0 before we test a char from the Original String

    Look at the code below; notice how the NewIndex variable will get created and init = 0 each time we need it.
    The NewIndex only lasts (has scope) in the 'if we found the word' bit of code. NewIndex does not exist if we did not find the Word and stops existing after that 'if' executes.

    Finally, you say add the 'new word' or single original character to output string, I really don't understand how this can be done.
    Code:
    if (WordFound == true)
    {
         int NewINdex = 0;
         //copy the new word to the output string char by char
         while(NewWord[NewIndex] != '\0') //look for the null terminator at the end of the NewWord
         {
                 OutputString[OutputIndex] = NewWord[NewIndex];
                 //move output index 
                 OutputIndex++;
                 NewIndex++;
          }
           //now move our main index
           MainIndex =+ lengthofWord;
    
           // so now MainIndex has moved past the Word we found 
           //and OutputIndex has moved past the end of the NewWord we added
           //NewIndex stops having scope (ceases to exist)
    }
    else 
    {
          //just copy a single char 
          OutputString[OutputIndex] = OriginalString [MainIndex];
          // move both indexes 1 character
          MainIndex++;
          OutputIndex++;
         
           //both indexs move one character and we search again..
    }
    Using pointers to do this is similar. Pointers replace the indexes. I think you need to get how to use the indexes clear in your head before moving on to pointers (IMO).

    EDIT: I am coding this off the top of my head, do not expect it to actually work.....

    OrigString[MainIndex + WordIndex] //note that this does not change the values of the indexes (they do not actually get added)
    Last edited by novacain; 04-24-2011 at 07:53 PM.
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. replacing string elements
    By Dorothy in forum C Programming
    Replies: 4
    Last Post: 06-17-2010, 09:40 AM
  2. Replies: 3
    Last Post: 10-14-2008, 05:56 PM
  3. Replacing a part of a string with an other???
    By pseudonoma in forum C Programming
    Replies: 10
    Last Post: 03-24-2008, 08:31 AM
  4. Replacing string in file
    By Spedge in forum C Programming
    Replies: 1
    Last Post: 08-19-2003, 02:53 AM
  5. replacing a part of a string
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 05-20-2002, 03:32 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21