编写一个函数,利用指针在字符串s中的指定位置pos处(这里插入的位置是从1开始,不是下标)插入字符串。插入的位置和内容是从键盘输入
要求:子函数 char *InsertStr(char *s,int pos,char *t)
【输入形式】
输入主串s,输入插入的子串t,输入插入位置pos。
【输出形式】
输出插入后字符串
【样例输入】
输入:
abcde
KOBE
2
【样例输出】
aKOBEbcde
这个题目怎么写?
#include <iostream>
#include <cstring>
using namespace std;
char* InsertStr(char* s, int pos, char* t) {
int len = strlen(s) + strlen(t);
char *tmp = new char[len + 1]; // 分配内存
int i;
for (i = 0; i < pos - 1; i++) { // 复制插入位置前的主串
tmp[i] = s[i];
}
for (int j = 0; j < strlen(t); j++, i++) { // 复制子串
tmp[i] = t[j];
}
for (int j = pos - 1; j < strlen(s); j++, i++) { // 复制插入位置后的主串
tmp[i] = s[j];
}
tmp[len] = '\0';
s = tmp; // s指向新空间
return s;
}
int main() {
char s[50];
char t[50];
int pos;
cin >> s >> t >> pos;
char * p = InsertStr(s, pos, t); // 插入子串
cout << p << endl; // 输出结果
return 0;
}
在线验证通过