关于#函数返回字符串#的问题,如何解决?

编写一个函数,利用指针在字符串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;
}

在线验证通过

img

https://www.bejson.com/runcode/cpp920/

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 以下回答来自chatgpt:
    1. 编写InsertStr(char s, int pos, char t)子函数的具体实现: 插入字符串t到主串s中的指定位置pos,可以分为以下几步: 1)求出原始字符串s的长度和插入字符串t的长度,即strlen(s)和strlen(t); 2)定义一个新的字符数组temp,长度为strlen(s) + strlen(t) + 1,用来存放插入后的字符串; 3)将s的前pos-1个字符复制到temp中,即使用memcpy(temp, s, pos-1); 4)将t复制到temp的第pos位开始插入,即使用strcpy(temp+(pos-1), t); 5)将s剩余的字符复制到temp中,即使用memcpy(temp+(pos-1)+strlen(t), s+pos-1, strlen(s)-pos+1); 6)将temp复制到s中,即使用strcpy(s, temp)。

    代码实现如下:

    void InsertStr(char *s, int pos, char *t){
        int slen=strlen(s);
        int tlen=strlen(t);
        char *temp=new char[slen+tlen+1];
        memcpy(temp, s, pos-1);
        strcpy(temp+(pos-1), t);
        memcpy(temp+(pos-1)+tlen, s+pos-1, strlen(s)-pos+1);
        strcpy(s, temp);
        delete[] temp;
    }
    
    1. 如何输入主串s,插入字符串t,以及插入位置pos: 可以使用C++中的标准输入流,即cin来输入字符串和位置。代码实现如下:
    char s[100], t[100];
    int pos;
    cout<<"输入主串s:";
    cin>>s;
    cout<<"输入插入的子串t:";
    cin>>t;
    cout<<"输入插入位置pos:";
    cin>>pos;
    
    1. 输出插入后的字符串: 可以直接将插入后的主串s使用cout输出。代码实现如下:
    cout<<"输出插入后的字符串:"<<s<<endl;
    

    完整代码如下:

    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    void InsertStr(char *s, int pos, char *t){
        int slen=strlen(s);
        int tlen=strlen(t);
        char *temp=new char[slen+tlen+1];
        memcpy(temp, s, pos-1);
        strcpy(temp+(pos-1), t);
        memcpy(temp+(pos-1)+tlen, s+pos-1, strlen(s)-pos+1);
        strcpy(s, temp);
        delete[] temp;
    }
    
    int main(){
        char s[100], t[100];
        int pos;
        cout<<"输入主串s:";
        cin>>s;
        cout<<"输入插入的子串t:";
        cin>>t;
        cout<<"输入插入位置pos:";
        cin>>pos;
    
        InsertStr(s, pos, t);
    
        cout<<"输出插入后的字符串:"<<s<<endl;
        return 0;
    }
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^