编写函数实现以下功能,并要求测试。
函数void Insert(char *s, char *t, int pos)将字符串t插入到字符串s中,插入的位置为pos。(不得使用库函数)
提示,插入过程中,需要考虑字符串s空间是否足够。如果不足够,需要重新分配更大的空间。
输出结果:
主要算法:
void Insert(char *a, char *b, int pos)
{
int i, len1 = 0, len2 = 0;
while (a[len1] != '\0')
len1++; \
while (b[len2] != '\0')
len2++;
for (i = len1 - 1; i >= pos - 1; i--)
a[i + len2] = a[i];
for (i = pos - 1; i < pos - 1 + len2; i++)
a[i] = b[i - pos + 1];
len1 += len2;
a[len1] = '\0';
for (i = 0; i < len1; i++)
cout << a[i];
cout << endl;
}
完整代码:
#include<iostream>
using namespace std;
void Insert(char *a, char *b, int pos);
int main()
{
char a[200], b[100];
cout << "请输入字符串a:";
cin >> a;
cout << "请输入字符串b:";
cin >> b;
int pos;
cout << "输入你要插入的位置:";
cin >>pos;
Insert(a, b, pos);
return 0;
}
void Insert(char *a, char *b, int pos)
{
int i, len1 = 0, len2 = 0;
while (a[len1] != '\0')
len1++; \
while (b[len2] != '\0')
len2++;
for (i = len1 - 1; i >= pos - 1; i--)
a[i + len2] = a[i];
for (i = pos - 1; i < pos - 1 + len2; i++)
a[i] = b[i - pos + 1];
len1 += len2;
a[len1] = '\0';
for (i = 0; i < len1; i++)
cout << a[i];
cout << endl;
}