views:

121

answers:

4

can you give me an example of deleting characters from an array of characters in c? I tried too much, but i didn't reach to what i want

That is what i did:

 int i;
 if(c<max && c>start) // c is the current index, start == 0 as the index of the start, 
                      //max is the size of the array
 {
                i = c;
      if(c == start)
                        break;

        arr[c-1] = arr[c];


 }
printf("%c",arr[c]);
+4  A: 

A character array in C does not easily permit deleting entries. All you can do is move the data (for instance using memmove). Example:

char string[20] = "strring";
/* delete the duplicate r*/
int duppos=3;
memmove(string+duppos, string+duppos+1, strlen(string)-duppos);
Helmut
+1  A: 

You have an array of characters c:

char c[] = "abcDELETEdefg";

You want a different array that contains only "abcdefg" (plus the null terminator). You can do this:

#define PUT_INTO 3
#define TAKE_FROM 9
int put, take;
for (put = START_CUT, take = END_CUT; c[take] != '\0'; put++, take++)
{
    c[put] = c[take];
}
c[put] = '\0';

There are more efficient ways to do this using memcpy or memmove, and it could be made more general, but this is the essence. If you really care about speed, you should probably make a new array that doesn't contain the characters you don't want.

Nathon
A: 

Here's one approach. Instead of removing characters in place and shuffling the remaining characters (which is a pain), you copy the characters you want to keep to another array:

#include <string.h>
...
void removeSubstr(const char *src, const char *substr, char *target)
{
  /**
   * Use the strstr() library function to find the beginning of
   * the substring in src; if the substring is not present, 
   * strstr returns NULL.
   */
  char *start = strstr(src, substr);
  if (start)
  {
    /**
     * Copy characters from src up to the location of the substring
     */ 
    while (src != start) *target++ = *src++;
    /**
     * Skip over the substring
     */
    src += strlen(substr);
  }
  /**
   * Copy the remaining characters to the target, including 0 terminator
   */
  while ((*target++ = *src++))
    ; // empty loop body;
}

int main(void)
{
  char *src = "This is NOT a test";
  char *sub = "NOT ";
  char result[20];
  removeSubstr(src, sub, result);
  printf("Src: \"%s\", Substr: \"%s\", Result: \"%s\"\n", src, sub, result);
  return 0;
}
John Bode