Char array-search-and-delete-characters-problem

Hi,

I'm trying to write a loop that searches through an array of characters, and looks for certain combinations. Then if it finds one such combination, say an "abc" within the char array "This is the alphabet: abcdefg...", I need it to simply remove this sequence from the char array, leaving only "This is the alphabet: defg...".
Now, the thing that confuses me is that it successfully DETECTS all these character sequences (I make it print a little line whenever it does, just for control), but removing them, I just can't seem to work out.
What I ended up doing was looping through one char array, and filling every char element from the first into a second (new) char array, UNLESS it notices these sequences, and in that case, I tell it to skip the next 3 or so elements. So roughly, it looks like this:

(first, to remove "abc" from the end of the array. [length is the length of the array])
1
2
3
4
5
6
7
8
  if(text[length-3]=='a' && text[length-2]=='b' && text[length-1] == 'c')
    {
    cout << "Found an abc at the end! Wohoo! " << endl;
    for(int p=0;p<(length-3);p++)
	{
	  newCharArray[p]=text[p];
	}
    }


The other search-and-delete loops work in the same way, and they all "find" the right stuff, but don't delete anything.

Do you see what I'm doing wrong here?
Thanks!
Last edited on
You can't "delete" from a character array. When you have a c-string, the null terminator is your friend. Anything that accepts a c-string as an argument basically does things until it finds a null terminator.

A simple example, to "delete" the last 2 characters:
1
2
3
char word[20] = {'t', 'e', 's', 't', '\0'};
word[2] = '\0';
cout << word;


Another thing about c-strings is that they work by passing addresses:
1
2
3
4
5
6
char word[20] = {'t', 'e', 's', 't', '\0'};
cout << word << '\n';  // prints "test"
cout << word[1] << '\n'; // prints "e", I passed a character, not an address
cout << &word[1] << '\n'; // prints "est"
// Getting a little fancy
cout << word + 1 << '\n';// also prints "est" 


All of the c-string <string.h> functions work the same way. To give you a hint to solve your porblem:
1
2
3
char word[20] = {'t', 'e', 's', 't', '\0'};
strcpy(word + 1, word + 2);
cout << word << '\n';
Last edited on
Awesome! Thanks! :)
Topic archived. No new replies allowed.