在C中拆分数组

假设我有一个数组,我想从某些索引范围中删除元素。

如果我提前知道数组的大小,数组中每个元素的大小,以及我想删除的索引范围,有什么方法可以避免复制新数组?

如果您不想使用新数组进行复制,您可以考虑在同一个数组中执行此操作,这是我所拥有的:

#include #include int main() { char str[] = "hello world"; int i , strt , end , j; setbuf ( stdout , NULL ); printf ("enter the start and end points of the range of the array to remove:\n"); scanf ("%d%d", &strt , &end); int len = strlen (str); for ( i = end; i >= strt ;i--) { str[i-1] = str[i]; for ( j = i+1; j <= len ; j++) { str[j-1] = str[j]; } len--; } printf ("%s" , str); return 0; } 

虽然此代码用于字符数组 ,但您也可以将该算法用于稍微修改的整数数组将其作为练习 )。

注意: - 这种方法效率不高,因为你可以看到复杂性的指数增加,所以我的建议只是使用复制新的数组方法

你好,你可以做那样的事情。

 int main(int ac, char **av) { char *str; int i; i = 0; str = strdup("Hello World"); while(str[i]) { if(i == 6) // 6 = W the range of the array you want to remove str[i] = '\0'; i++; } printf("%s\n", str); } 

输出将是“Hello”而不是“Hello World”。