-tthappy 2023-03-25 17:27 采纳率: 55.6%
浏览 22
已结题

求解答关于字符串插入问题

求解答!
题目是:设计一个算法void insert(char*s,char *t,int pos)将字符串t插入到字符串s中。
原来是想把字符串t1从从最后一个字符开始依次往后移,直至pos;此时已经留了足够的空位、
再将t2中字符串插入,
但是我的运行结果是,t1中原来那些往后移的字符居然不见了?想了很久都没想出来。求指出。

img

#include <stdio.h>
#include <string.h>
#define MAXSIZE 255
typedef struct   //串的顺序存储结构,从ch[1-lenth] 储存字符,ch【0】为空 
{char ch[MAXSIZE+1];
int lenth;
}SString;
void insert (SString t1,SString t2,int pos)   //插入函数 
{
for(int i=t1.lenth;i<=pos;i--)     //先将要t1中pos及后面的字符往后移,将中间留出t2字符串的长度 
{ t1.ch[i+t2.lenth]=t1.ch[i];        //将t1中最后一个字符开始往后移 
 } 
 int j=1;
 for (int i=pos;i<pos+t2.lenth&&j<=t2.lenth;i++,j++) //然后将字符串t2直接插入t1中 
 t1.ch[i]=t2.ch[j];
 t1.lenth=t1.lenth+t2.lenth;
 int i=1;
 printf("%s",t1.ch+1);

}
int main()
{SString t1,t2;         
printf("请输入第一个字符串数组的长度\n");    //输入字符串1 
int n;
scanf("%d",&n);
t1.lenth=n;
scanf("%s",t1.ch+1);
printf("请输入第二个字符串数组的长度\n");    //输入字符串2 
scanf("%d",&n);
t2.lenth=n;
scanf("%s",t2.ch+1);
int pos;
printf("请输入你要插入的位置\n");
scanf("%d",&pos);
insert(t1,t2,pos);      //插入 
return 0;

}
  • 写回答

2条回答 默认 最新

  • 少林and叔叔 2023-03-25 18:40
    关注

    程序几个地方有问题,修改后的见最后,具体分析如下:
    1.第一个for循环这里有问题:for(int i=t1.lenth;i<=pos;i--),i<=应该修改为i>=;
    2.第二个for循环这里也有问题:for (int i=pos;i<pos+t2.lenth&&j<=t2.lenth;i++,j++);修改为一个参数即可;
    3.给数组参数输入值为什么要+1,那不是第一个元素无效了,这里也进行了修改。
    如有不明白的,可私信。

    #include <stdio.h>
    #include <string.h>
    #define MAXSIZE 255
    typedef struct   //串的顺序存储结构,从ch[1-lenth] 储存字符,ch【0】为空 
    {char ch[MAXSIZE];
    int lenth;
    }SString;
    void insert (SString t1,SString t2,int pos)   //插入函数 
    {
    for(int i=t1.lenth;i>=pos;i--)     //先将要t1中pos及后面的字符往后移,将中间留出t2字符串的长度 
    { t1.ch[i+t2.lenth]=t1.ch[i];        //将t1中最后一个字符开始往后移 
     } 
     //int j=1;
     for (int i=pos;i<pos+t2.lenth;i++) //然后将字符串t2直接插入t1中 
     t1.ch[i]=t2.ch[i-pos];
     t1.lenth=t1.lenth+t2.lenth;
     //int i=1;
     printf("%s",t1.ch);
     
    }
    int main()
    {SString t1,t2;         
    printf("请输入第一个字符串数组的长度\n");    //输入字符串1 
    int n;
    scanf("%d",&n);
    t1.lenth=n;
    scanf("%s",t1.ch);
    printf("请输入第二个字符串数组的长度\n");    //输入字符串2 
    scanf("%d",&n);
    t2.lenth=n;
    scanf("%s",t2.ch);
    int pos;
    printf("请输入你要插入的位置\n");
    scanf("%d",&pos);
    insert(t1,t2,pos);      //插入 
    return 0;
     
    }
    ```c
    
    
    

    ```

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月2日
  • 已采纳回答 3月25日
  • 创建了问题 3月25日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度