#include<iostream> #include<string> #include<cstring> using namespace std; int s_l = 0, t_l = 0; void insert(char *s, char *t, int pos) { char *ptr; for (ptr = s; *ptr != ‘\0‘; ptr++) { s_l++; } for (ptr = t; *ptr != ‘\0‘; ptr++) { t_l++; } for (int i =s_l;i>=pos-1;i--) { s[i+t_l]=s[i]; } int c = 0; for (int i = pos - 1; i < pos + t_l-1; i++) { s[i] = t[c]; c++; } } int main() { int pos; char s[1000],t[1000]; while (cin >> pos && pos != 0) { cin >> s >> t; insert(s, t, pos); for (int i = 0; i <s_l+t_l-1; i++) { cout << s[i]; } cout << s[s_l + t_l - 1] << endl; s_l = t_l = 0; } //system("pause"); return 0; }
描述
编写算法,实现下面函数的功能。函数void insert(char*s,char*t,int pos)将字符串t插入到字符串s中,插入位置为pos(插在第pos个字符前)。假设分配给字符串s的空间足够让字符串t插入。(说明:不得使用任何库函数)
输入
多组数据,每组数据有三行,第一行为插入的位置pos,第二行为要被插入的字符串s,第三行为待插入的字符串t。当pos为“0”时输入结束。
输出
对于每组数据输出一行,为t插入s后的字符串。
输入样例 1
1 abcde abc 2 acd baaaa 0
输出样例 1
abcabcde abaaaacd
问题:1、把t插入到s中,循环的次数弄错了
2、字符数组的长度:
char *ptr;
for (ptr = s; *ptr != ‘\0‘; ptr++)
{
s_l++;
}
for (ptr = t; *ptr != ‘\0‘; ptr++)
{
t_l++;
}
原文:https://www.cnblogs.com/h694879357/p/11762709.html