拆分C​​中的数组 [英] Splitting an Array in C

查看:106
本文介绍了拆分C​​中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组,我想删除从指数的一定范围内的元素。

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 array, and what ranges of indices I want to remove is there any way I can avoid copying over a new array?

推荐答案

如果你不想使用复制一个新的数组,你可以认为在同一阵列本身在做这个的,这里是我有:

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

虽然这code是对于字符数组上,您还可以使用整型数组稍作修改(算法做锻炼)。

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 .

这篇关于拆分C​​中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆