/*write a program to insert a string into main string*/
#include <stdio.h>

int main()
{
    char text[100], str[20], ins_text[100];
    int i = 0, j = 0, k = 0, pos;
    printf("enter main text: ");
    gets(text);
    printf("enter string to be inserted: ");
    gets(str);
    printf("enter the position to be inserted: ");
    scanf("%d", &pos);

    while (text[i] != '\0')
    {
        if (i == pos)
        {
            while (str[k] != '\0')
            {
                ins_text[j] = str[k];
                j++;
                k++;
            }
        }
        else
        {
            ins_text[j] = text[i];
            j++;
        }
        i++;
    }

    ins_text[j] = '\0';
    printf("\n the new string is: ");
    puts(ins_text);
    return 0;
}

在航站楼

$ ./a.exe

enter main text: newsman
enter string to be inserted: paper
enter the position to be inserted: 4

The new string is: `newspaperan`

在上面的最终输出中:-"新字符串是:Newspperan",字母"m"缺失. 我认为这是因为在While循环中增加了"j++"; 有什么办法修好它吗?

推荐答案

这就是导致你问题的其他原因.当你在中间插入这个词时,你必须像往常一样在后面继续.

while (text[i] != '\0') {
    if (i == pos) { // insert the word
        while (str[k] != '\0') {
            ins_text[j++] = str[k++];
        }
    }
    ins_text[j++] = text[i++];
}

C++相关问答推荐

Bison解析器转移/减少冲突

你能用自己的地址声明一个C指针吗?

使用SWI—Prolog的qsave_program生成二进制文件有什么好处?'

GCC:try 使用—WError或—pedantic using pragmas

va_copy的使用是未定义的行为吗?

ESP32在vTaskDelay上崩溃

在Rust和C之间使用ffi时如何通过 struct 中的[U8;1]成员传递指针

从C文件中删除注释

关于scanf()和空格的问题

收到不兼容的指针类型警告,因为函数的返回不是空*,而是 struct 指针

这段代码用于在C中以相反的顺序打印数组,但它不起作用

将数字的每一位数平方,并使用C将它们连接为一个数字(程序不能正确处理0)

用C++高效解析HTTP请求的方法

Fscanf打印除退出C代码为1的程序外的所有内容

将某些内容添加到链接列表时,列表中的其他项将使用最后添加的项的名称

用C++初始化局部数组变量

`%%的sscanf无法按预期工作

WSASocket在哪里定义?

为什么孤儿进程在 Linux 中没有被 PID 1 采用,就像我读过的一本书中声称的那样?

int 与 size_t 与 long