2010-10-28 31 views
0

你能给我一个从c中的字符数组中删除字符的例子吗? 我想太多了,但我没有达到我想要什么如何使用C中的baskspace从字符串中删除一个字符?

这就是我所做的:

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]); 
+2

你能更改标题?你不是在讨论用户输入事件......也许就像“如何从C中的字符串中删除子字符串?” – andrewmu 2010-10-28 16:29:58

+0

这不起作用,您需要for循环或memmove。就复杂性而言,它必须是O(n)。 – 2010-10-28 16:38:28

+0

@andrewmu ok,根据你的建议更改 – noor 2010-10-28 16:38:31

回答

4

C中的一个字符数组不会轻易允许删除条目。你所能做的就是移动数据(例如使用memmove)。例如:

char string[20] = "strring"; 
/* delete the duplicate r*/ 
int duppos=3; 
memmove(string+duppos, string+duppos+1, strlen(string)-duppos); 
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,它可以变得更加普遍,但这是本质。如果你真的关心速度,你应该创建一个不包含你不想要的字符的新数组。

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

串= HELLO \ 0

STRING_LENGTH = 5(或者只是使用内部strlen的,如果你不想缓存它这种外呼

,如果你想删除“E”

拷贝到“E”位置remove_char_at_index = 1(串+ 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); 

} 
相关问题