Suppose I have an array and I want to remove elements from certain ranges of indices.
If I know ahead of time the size of the array, the size of every element in the arr
If you don't want to use a new array for copying , you can think of doing this in the same array itself , here is what I have :
#include<stdio.h>
#include<string.h>
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;
}
While this code is for character arrays, you can also use the algorithm for integer arrays with slight modifications (do it as exercise ).
NOTE:- This method is not very efficient though , as you can see the exponential increase in the complexity , so my advice would be just to use the copying over new array method .
Hello you could do something like that.
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);
}
The output will be "Hello" instead of "Hello World".