String Replace With a Substring

Replace all occurrences of a substring within a string by another substring. For example, if the
original string is:
"abcllo abcre I am". The substring to replace is "abc" and it is to be replaced by "he", then the
string to return is: "hello here I am".


Yes, this is my homework, so I won't ask for the code. I know how to replace a single character, here is my code for that:

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
#include <iostream>
using namespace std;

void main()
{
	char ch,ch2;
	const int size = 50;
	char array_1[size];

	cout << "Enter a string: ";
	cin.getline(array_1,size,'\n');

	cout << "Enter a character you want to replace: ";
	cin >> ch;

	cout << "Enter a character you want to replace '" << ch << "' character with: ";
	cin >> ch2;

	for(int i=0; array_1[i] != '\0'; i++) {
		if(array_1[i] == ch)
			array_1[i] = ch2;
	}

	cout << "Here is the new string: " << array_1 << endl;

	system("pause");
}


But how to replace a number of characters with another string? I gotta do it without using any built-in function. I'm also not allowed to use the string data-type from <string> or <cstring>.

I'd be thankful if anybody can give me hint about how to solve it in easiest and shortest way.

Thank you.
Last edited on
Have char array_2[size];. Then for each char in array_1, "abc" starts from it (you need a string comparison function. I'll assume you know how to write it) append "he" to array_2. Otherwise, append that char to array_2.
This will be just two nested loops - outer for each char of array_1 and inner to compare the current substring to "abc".
Thank you, hamsterman. I read your answer like five times, but I couldn't understand it fully.

But let me try, I will post here my code whether I succeed or not.
Start from the beginning. Can you write a function that, given two char*, can tell if the first one begins with the second one? That is, cmp("abcde", "abc") returns true, and cmp("foo", "bar") returns false.
Yes, I can write that function.

1
2
3
4
5
6
7
8
9
10
11
int strcmp(char myString_1[],char myString_2[])
{
	for(int count=0; (myString_1[count] != '\0' && myString_2[count] != '\0'); count++) {

		if(myString_1[count] != myString_2[count]) {
			return 0;
		}
	}

	return 1;
}
Last edited on
Okay. Now, write a few more functions.

One that given two strings, iterates through the first one and for each char in it, checks (using your strcmp) if the second one starts at it. If it does, print '*'. A thing that you may not be aware of is that a pointer to a string that starts with mystring[count] is (mystring+count). Example:
1
2
your_function("banana", "an");//output - **
your_function("aaaaa", "aa")//output - ** 
You need this function not to print a '*' twice for the same char. That is in the aaaaa example, it could seem natural to find AAaaa, aAAaa, aaAAa and aaaAA, but you should only accept AAaaa and aaAAa. To achieve this, after printing a *, move the counter forward by the length of the second string.

One that given two strings and a position in the first one, pastes the second one into the first one at the given position. Example:
1
2
3
char str[50] = "hello";
your_function(str, " world", 5);
cout << str;//prints "hello world" 


One that given an empty char array and a string copies the string into the array duplicating any 'a's. The idea is to use two separate counters for both strings. Example:
1
2
3
char str[50];
your_function(str, "banana");
cout << str;//prints "baanaanaa" 


The solution of your assignment is a combination of all of these.
Last edited on
I have written a function that can find a substring in a larger string. I'm unable to figure out how to modify it to replace the substring with another string.

This function below will find out the indices of the substring.

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
42
void strFindindex(char myString_1[], char myString_2[],int indices[],int &count)
{
	int k,found;
	count=0;
	for(int i=0; myString_1[i] != '\0'; i++) {
		k=i;
		found = 1;
		for(int j=0; myString_2[j] != '\0'; j++) {
			if(myString_2[j] != myString_1[k])
				found = 0;
			k++;
		}
		if(found) {
			indices[count] = i;
			i=k;
			count++;
		}
	}
	
}

void main()
{
	const int size=50;
	char myString_1[size], myString_2[size];
	int indices[size];
	int isize,i;

	cout << "\n\t[*] Type a string/sentence: ";
	cin.getline(myString_1,size);

	cout << "\n\t[*] Enter the substring that you want to find: ";
	cin >> myString_2;
	strFindindex(myString_1,myString_2,indices,isize);
	cout << "\n\t\t[!] Substring was found on indices: ";
	for(i=0; i<isize; i++)
		cout << indices[i] << " ";
	cout << endl << endl;

	system("pause");
}
At least do the last one in my list (one with duplicating 'a's) ...

By the way, variable k is sort of unnecessary as it is equal to i+j. You'd have to fix the scope of j if you wanted to remove k though.
Also, it would be more appropriate to make variable found a bool.
I'd be thankful if anybody can give me hint about how to solve it in easiest and shortest way.


The shortest way is to use the boost library

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <boost/algorithm/string.hpp>
using namespace std;
int main()
{
    cout << "Enter a string: ";
    string array_1;
    getline(cin, array_1);

    cout << "Enter a string you want to find: ";
    string ch;
    getline(cin, ch);

    cout << "Enter a string you wish to replace " << ch << " with: ";
    string ch2;
    cin >> ch2;

    boost::replace_all(array_1, ch, ch2);

    cout << "Here is the new string: " << array_1 << '\n';
}

demo: http://ideone.com/iIWT7

Using plain C++, consider a loop that does http://www.cplusplus.com/reference/string/string/find/ and http://www.cplusplus.com/reference/string/string/replace/ -- that may be easier than all this array business.

Something like

1
2
3
4
5
6
    for(size_t pos = array_1.find(ch); pos != std::string::npos;
               pos = array_1.find(ch, pos))
    {
        array_1.replace(pos, ch.size(), ch2);
        pos += ch2.size();
    }

demo: http://ideone.com/4qCud

Don't forget to fix that "void main" error (try your program on ideone.com)

PS: Just noticed the "not allowed to use string".. oh well, this would be something ot keep in mind when you can use C++
Last edited on
I have made the program. Thank you everybody. Special thanks to hamsterman.

I would be even more thankful if anybody provides me the code for an easier solution, so that I can learn from it.

Here's my code. I'm sure it needs improvements. I will try to improve, if anybody points out where it needs any improvement.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
using namespace std;


void strReplaceSubStr(char [], char [], char [], char []);

int main()
{
	//declaring and initializing req. variables
	const int size = 50;
	char myString_1[size], myString_2[size];
	char myString_3[size];
	char thenewString[50];

	//getting input (a string) from the user
	cout << "\n\t[*] Type a string/sentence: ";
	cin.getline(myString_1,size);

	cout << "\t[*] Enter the substring that you want to find: ";
	cin >> myString_2;
	cout << "\t[*] Enter the substring that you want to replace with: ";
	cin >> myString_3;
	strReplaceSubStr(myString_1,myString_2,myString_3,thenewString);
	cout << "\n\t\t[!] Replaced string: " << thenewString << endl << endl;

	system("pause");
	return 0;
}


void strFindindex(char myString_1[], char myString_2[],int indices[],int &count)
{
	int k,found;
	count=0;
	for(int i=0; myString_1[i] != '\0'; i++) {
		k=i;
		found = 1;
		for(int j=0; myString_2[j] != '\0'; j++) {
			if(myString_2[j] != myString_1[k])
				found = 0;
			k++;
		}
		if(found) {
			indices[count] = i;
			count++;
		}
	}
}

//it will calculate and return the length of the string
int lengthOf(char myString_1[])
{
	int count;
	for(count=0; myString_1[count] != '\0'; count++);
	return count;
}

//will append a string to another string
void append(char newString[],char myString_3[],int &pos)
{
	for(int i=0; myString_3[i] != '\0'; i++) {
		newString[pos] = myString_3[i];
		pos++;
	}

}

//this function will replace a substring with another string
void strReplaceSubStr(char myString_1[], char myString_2[], char myString_3[], char newString[])
{
	int indices[50];
	int isize,inum=0,pos=0;
	//will stores indices in "indices" array
	strFindindex(myString_1,myString_2,indices,isize);
	int length = lengthOf(myString_3);
	int length2 = lengthOf(myString_2);

	for(int i=0; myString_1[i] != '\0'; i++) {
		if(i == indices[inum]) {
			//myString_3 will be appended in newString
			append(newString,myString_3,pos);
			inum++;
			i = i+length2-1;
		}
		else {
			newString[pos] = myString_1[i];
			pos++;
		}
	}

	newString[pos] = '\0';
}
Last edited on
Topic archived. No new replies allowed.