【问题标题】:Copying part of a character array to another array in C将字符数组的一部分复制到C中的另一个数组
【发布时间】:2013-11-05 18:04:03
【问题描述】:

所以我一直在尝试解决以下问题,但无济于事:

编写一个名为 removeString 的函数以从字符串中删除指定数量的字符。该函数应采用三个参数:源字符串、源字符串中的起始索引号以及要删除的字符数。因此,如果数组文本中包含字符串“错误的儿子”,则调用

removeString(文本, 4, 6);

具有从数组文本中删除字符“wrong”(单词“wrong”加上后面的空格)的效果。文本中的结果字符串是“儿子”。

我已经尝试查找其他解决方案,但它们都使用 memcpy 函数,我想避免使用它,因为它还没有在我的书中介绍,我不想“欺骗系统”可以这么说。

我的 removeString 函数如下:

void removeString (char text[], int x, int y)
{
    char output[81];
    int i, z = 0;
        
    for ( i = 0; (i <= 81); i++) {
            
        if (z < (x-1) || z > (x+y-1) ) {
            output[z] = text[z];
            //printf("%i\n", z);
            z++;
        } else {
            z++;
        }
            
    }
        
}

int main(void)
{
    char s1[81] = "the wrong son";
    int startPoint = 4, runLength = 6;
    
    removeString(s1, startPoint, runLength);
    
    printf("The new text is as follows:\n");
    printf("%s\n", s1);
    
    return 0;
}

当我打印出“z”的值时,我看到它正在跳过数字,但由于某种原因,它看起来像是将所有 text[] 复制到 output[] 中。

【问题讨论】:

标签: c arrays string


【解决方案1】:

这将对原始字符串起到作用

for (;text[x];x++)
{
  text[x]=text[x+y];
}

【讨论】:

    【解决方案2】:
               output[z] = text[z];
    

    这意味着新数组中的每个元素都将在与原始元素相同的索引中。此外,您需要将输出作为参数而不是在本地声明:

    void removeString (char text[], char output[], int x, int y)
    {
        for(int i = 0; i < x; i++)
            output[i] = text[i];
    
        for (int i = y; text[i] != '\0'; i++)
            output[i - (y - x)] = text[i];
    
    }
    
    int main(void)
    {
        char s1[81] = "the wrong son";
        char output[81];
        int startPoint = 4, runLength = 6;
    
        removeString(s1, output, startPoint, runLength);
    
        printf("The new text is as follows:\n");
        printf("%s\n", s1);
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-03
      • 2010-10-18
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多