removing a substring

Hello.
I have a C-based string. trying to remove some sub-string, I got at:
1
2
3
4
char str[]="alireza tavakkoli";
char* pos = strstr( str, "reza");
for(int j=pos-&str[0];j<pos-&str[0]+strlen("reza");++j)
str[j] = 7;


But I don't like the last line.isn't there a better solution?

To 'remove' a substring, you'll need to shift the following characters over to fill the void.

str[j] = str[j+1]

Replaces the jth character with the following character. This shifts everything over to the left, essentially removing the substring. You'll need to adjust your loop so you iterate over the entire character array after the start of the substring.
I prefer to substitute the specific characters with
0x7
. It sounds more efficient, although using
strlen()
on the string would return the length of the original string.

Anyway, I ran into the problem of locating the exact match of the sub-string. I want 'a' to be matched against an indefinite article, not against any occurance of "a", as 'a' in 'health'.Anyway I can do that?
Last edited on
Substitution works, though your string will just continue to grow, and you don't actually gain any performance.

For your needs now, I highly recommend using regex. If you have a C++11 compiler, check out the <regex> header. If you haven't looked at any regex before, don't be scared at how it looks. It's really not as complicated as it looks.
I have dev-c++, which was built 6 years before 2011
Last edited on
Uh well that's an issue you need to correct right now. Either go download an up-to-date version of dev-C++ (I think Orwell?) or go download a better IDE. Code::Blocks is a great free IDE, which comes with an up-to-date toolchain.
But I don't have much time, to first lean C++ 11 and then do the exercise. Cannot you suggest a way around my problem? There needs to be a way...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cstring>

using namespace std;

int main() {
	char str[]="alireza tavakkoli";
	char str2[20];
	
	int d = strstr(str, "reza") - &str[0];
	strncpy(str2,str, d);
	strcat(str2, &str[d + strlen("reza")]);
	
	cout << str2 << endl;
}
Topic archived. No new replies allowed.