如何在C中使用退格键从字符串中删除字符?

时间:2010-10-28 16:24:09

标签: c arrays pointers character-arrays

你能给我一个从c中的字符数组中删除字符的例子吗? 我尝试了太多,但我没有达到我想要的目标

这就是我所做的:

 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 个答案:

答案 0 :(得分:4)

C中的字符数组不容易删除条目。您所能做的就是移动数据(例如使用memmove)。例如:

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

答案 1 :(得分:1)

你有一个字符数组c:

char c[] = "abcDELETEdefg";

你想要一个只包含“abcdefg”的不同数组(加上空终止符)。你可以这样做:

#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';

使用memcpy或memmove有更有效的方法可以做到这一点,并且它可以更通用,但这是本质。如果你真的关心速度,你应该制作一个不包含你不想要的角色的新数组。

答案 2 :(得分:1)

这是一种方法。您可以将要保留的字符复制到另一个数组中,而不是删除到位的字符并将剩余字符移动(这很痛苦):

#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;
}

答案 3 :(得分:0)

string = H E L L O \ 0

string_length = 5(如果您不想在此调用之外将其缓存,请在内部使用strlen

如果要删除“E”

,请

remove_char_at_index = 1

复制到'E'位置(字符串+ 1)

从第一个'L'位置(字符串+ 1 + 1)

4个字节(想要得到NULL),所以5 - 1 = 4

remove_character_at_location(char * string, int string_length, int remove_char_at_index) {

    /* Use memmove because the locations overlap */.

    memmove(string+remove_char_at_index, 
            string+remove_char_at_index+1, 
            string_length - remove_char_at_position);

}