assignment: replaceSubstring Function

Pages: 12
Hi all, I've written most of the code for this assignment, however I'm stuck on one part. Here's the assignment:

Write a function named replaceSubstring. The function should accept three C-string or string object arguments. Let's call them string1, string2, string3. It should search string1 for all occurrences of string2. When it finds an occurrence of string2, it should replace it with string3. For example, suppose the three arguments have the following values:

string1: "the dog jumped over the fence"
string2: "the"
string3: "that"

With these three arguments, the function would return a string object with the value "that dog jumped over that fence". Demonstrate the function in a complete program.


My problem is, when I have the user input the string3, I'm not sure how I should go about replacing anything found with string2 in string1.

Here is my current code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
using namespace std;

int main()
{
	const int LENGTH = 80;
	char string1[LENGTH];
	char string2[LENGTH];
	char string3[LENGTH];

	char *strPtr;

	//read strings
	cout << "Enter a string to be read: ";
	cin.getline(string1, LENGTH);

	cout << "Enter the search string: ";
	cin.getline(string2, LENGTH);

	cout << "Enter the string to replace the search string with: ";
	cin.getline(string3, LENGTH);

	strPtr = strstr(string1, string2);
	
	if (strPtr == NULL)
	{
		cout << "Nothing found" << endl;
	}

	if (strPtr)
	{
		cout << "found";
	}
	
	system("PAUSE");
	return 0;
}
Last edited on
Just rewrite the string character by character. If there's the to-be-replaced string at the current position, append the replacement string, otherwise append the current character.
If you want to use strstr, you have to append the entire substring between any matches you found.
Last edited on
I get what your saying, however I don't know the syntax for that. How can you find positions in a char?
You access the character at index i with str[i]. If you want to find a substring in a C string, you can use strstr. When you use std::string (which you should do), use the find member function. See:
http://www.cplusplus.com/reference/string/string/
demetri90 wrote:
Write a function named replaceSubstring. The function should accept three C-string or string object arguments.


Do you think you would be allowed to write the function to accept an object of string objects? I ask because the first thing I thought after reading your question was vectors.

You could read in a line of text, separate each individual word in that text, storing them in a vector of string. Then you can search that vector one element at a time, checking each value against the search word, and finally switching any found words with the choosen replacement.
Last edited on
However, the assignment does not state that the strings are restricted to words.
It seems like my code now can find each letter, it's the replacing part I'm unsure about. The vector idea seems sound, however I wouldn't have the slightest clue on writing all of that.
Last edited on
Like I said, create a new string and assemble it bit by bit. Instead of the replaced string, append the replacement, otherwise append the original.
Last edited on
So your saying I can't use the strstr method? If it finds the string2 in string1, append it with string3, else append the rest of string1?
You can use strstr just fine. Instead of iterating over the characters, you'd iterate over each match.
Same concept.
so the string to search for can be multiple words? hmm, is it possible to count the number of words in the search string (X), then iterate over all sets of X consecutive words in the original text until (or if) a matching phrase is found?

EDIT: nvm, I never knew that strstr() was a member function. I had just assumed it was your user defined function to replace the strings.

It's fun to learn new things!
Last edited on
Ugh my brain is going to explode. So with the strstr(), you can find matches instead of individual characters? Basically whole words?
Not just words, any arbitrary part of a sentence. Since you used strstr, I figured you knew how it works. See:
http://www.cplusplus.com/reference/clibrary/cstring/strstr/
Last edited on
Ok I messed around a bit with the strncpy as showed in that link, however I get different results.

If I enter for string1: "the dog
If I enter for string2: "the"
If I enter for string3: "that"

I get "that" printed. When It should print "that dog"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;

int main()
{
	const int LENGTH = 80;
	char string1[LENGTH];
	char string2[LENGTH];
	char string3[LENGTH];

	char *strPtr;

	//read strings
	cout << "Enter a string to be read: ";
	cin.getline(string1, LENGTH);

	cout << "Enter the search string: ";
	cin.getline(string2, LENGTH);

	cout << "Enter the string to replace the search string with: ";
	cin.getline(string3, LENGTH);

	strPtr = strstr(string1, string2);

	if (strPtr == NULL)
	{
		cout << "Nothing found" << endl;
	}

	if (strPtr)
	{
		cout << "found" << endl;
		strncpy (strPtr,string3,6);
		puts (string1);
	}
	
	system("PAUSE");
	return 0;
}
That's because the '6' in strncpy (strPtr,string3,6);
should be a '4' (or, more generally, the length of the replacement string)
strncpy (strPtr, string3, strlen(string3);

But that seems to introduce another problem: the replacement string is overwriting characters in the original string.

I ran the code with
string1 = "the dogs"
string2 = "the"
string3 = "those"

with output:
found
thoseogs


Last edited on
Ok that helped, however it kills the space in between.

Basically outputs thatdog
Yeah, that's because you're overwriting the original string. You can't do that, because the replacement string can have any length.
Ah, so basically this isn't the way to go then.
Alright Athar, basically this is what your saying:

1
2
	//psuedocode
	string4 = word + word + replacedword + word
Yes, more or less. Since the replacing is not restricted to entire words, it would be:
string4=character + character + [...] + replacedString + character + [...];

It's a primitive solution, but since it's so simple, there's no room for messing up.

With C++ strings, it would look as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::string replaceSubstring(const std::string& string1,const std::string& string2,const std::string& string3)
{
    std::string newString;
    for (size_t i=0;i<string1.length();i++)
    {
        if (string1.substr(i,string2.length())==string2)
        {
            newString+=string3;
            i+=string2.length()-1; //skip other matched characters
        }
        else newString+=string1[i];
    }
    return newString;
}


When you want to use C strings, you can replace the appending with strcpy etc.
The concept remains the same.
Pages: 12