求解答!
题目是:设计一个算法void insert(char*s,char *t,int pos)将字符串t插入到字符串s中。
原来是想把字符串t1从从最后一个字符开始依次往后移,直至pos;此时已经留了足够的空位、
再将t2中字符串插入,
但是我的运行结果是,t1中原来那些往后移的字符居然不见了?想了很久都没想出来。求指出。
#include
#include
#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//然后将字符串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;
}
程序几个地方有问题,修改后的见最后,具体分析如下:
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
```
不知道你这个问题是否已经解决, 如果还没有解决的话:void fun(char* s, char* t, char* p)
{
int i, j,c=0;
for (j = 0; *(t + j); j++)//外层循环遍历t数组
{
int f = 0;//标志符号
for (i = 0; *(s + i); i++)//内层循环遍历s数组
if (*(t + j) == *(s + i))//当s中有元素与t中的元素相等时
f = 1;//将标识符置为1
if (f == 0)//如果内存循环一轮结束后标识符没有改变,说明s中没有元素与t相等,即满足题目要求
{
*(p + c) = *(t + j);//拷贝这个元素到p中
c++;
}
}
*(p + c) = '\0';
//判断是否重复
for (c = strlen(p); c>=0; c--)//外层内存循环都是p数组,从后往前遍历是为了保证题目要求p中字符按原字符串的顺序排列
{
int f = 0;//标识位刚开始置为0
for (i = 0; *(p+i); i++)
if (*(p + c) == *(p + i))
{
f++;
if (f >= 2)//当发现有重复元素大于等于2个时
{
for (j = c; *(p + j); j++)
*(p + j) = *(p + j + 1);//删去这个重复的元素
f--;
}
}
}
puts(p);
}