如何在C中的字符串中插入一个额外的字符

How to insert an extra character in a string in C

#include <stdio.h>
#include <string.h>

void replace(char a[],char b[]);

int main(void)
{
    char string1[100]; char string2[100];
    printf("Please enter a string:");
    fgets(string1, sizeof(string1), stdin);

    replace(string1, string2);
}

void replace(char a[],char b[])
{
    int i;
    strcpy(b,a);

    for(i=0;i<strlen(a);i++)
    {
        if(a[i]=='a')
        {
            b[i+1]=a[i];
        }
    }

    printf("%s\n",b);
}

这个程序的功能是将string1复制到string2中,但是如果string1中有任何'a'字符,则需要在[=12中加倍=].

例如,如果 string1 为 "aeroplane",则 string2 需要为 "aaeroplaane"。

但是,上面的代码似乎更改了 string1'a' 之后的下一个字符,而不是简单地添加它。例如,如果我输入 "aloha",它只会给我 "aaoha" 而不是 "aalohaa"。我试过在线搜索但无济于事。我已经坚持这个问题好几个小时了。

b[i+1]=a[i]

您正在将下一个字符更改为 'a' 并覆盖下一个字符。 应该做的是将 b[i+1] 之后的所有字符向前移动一步,然后将 b[i+a]

中的 'a'

我不会帮你解决的。 但这是您需要研究的内容。

if(a[i]=='a')
{
    b[i+1]=a[i];
}

它正在做的是,如果 a 数组的第 i 个索引是 'a',则将 a 数组的第 i 个索引写入 i+1数组的第b.

位置

这样你就覆盖了 b 的内容。 只有在将字符串从该索引向右移动 之后,您才需要在此处放置一个额外的字符 。 可以通过多种方式完成。

此外,您可能想要分配更多的大小(理想情况下是两次:为了涵盖当您将 string1 传递给 100 'a' 时的情况,生成的 string2 应该包含 200 'a's) 到你的第二个阵列而不是第一个,因为显而易见的原因。

为了工作,您必须正确实施 replace 功能

应该是这样的:

void replace(char a[],char b[])
{
    int idxA = 0, idxB = 0;

    for(idxA;idxA<strlen(a);idxA++, idxB++)
   {
        b[idxB] = a[idxA];
        if(a[idxA]=='a')
        {
            idxB++;
            b[idxB]=a[idxA];
        }
    }

    b[idxB] = '[=10=]';
    printf("%s\n",b);
}

但您必须确保 b 有足够的 space 来容纳完整的字符串。例如,您可以保留 a 大小的两倍,最坏的情况是数组 a 具有所有 a 个字符

你想要这个:

#include <stdio.h>
#include <string.h>

void replace(char a[], char b[]);

int main(void)
{
  char string1[100]; char string2[100];
  printf("Please enter a string:");
  fgets(string1, sizeof(string1), stdin);

  replace(string1, string2);

  printf("%s\n", string2);      // printf result from replace here
}


void replace(char a[], char b[])
{
  int i, j;   // using two indexes, one for a and one for b

              // no strcpy needed here, copying is done in the for loop below       

  for (i = 0, j = 0; i < strlen(a); i++, j++)
  {
    b[j] = a[i];        // copy one char

    if (a[i] == 'a')    // if it's 'a'
    {
      b[++j] = a[i];    // copy it again
    }
  }

  b[j] = 0;             // terminate the destination string
                        // we don't printf b here but in main
}

为简洁起见,此处未进行缓冲区溢出检查。

虽然还有改进的空间。

void replace(char a[],char b[])
{
    int i = 0, j = 0;
    for(i=0; i<strlen(a); i++, j++)
    {
        b[j] = a[i];
        if(a[i] == 'a')
            b[++j] = a[i];
    }
}

看看这是否有效。

好的,如果我们玩代码高尔夫,我建议:

void replace (char *a, char *b) {
        while ((*b++ = *a)) 
                if (*a++ == 'a')
                        *b++ = 'a';
}

;)

介意在b中提供足够的内存;如果您想安全起见,它必须至少是 strlen(a)*2+1(案例 a 仅包含字符 "a")。

为了简洁和优雅,这里有一个衬里:

void replace (char *a, char *b) { while((*b++=*a)&&(*a++!='a'||(*b++='a'))); }

;)