插入字符串

来源:互联网 发布:js实现中英文切换代码 编辑:程序博客网 时间:2024/05/16 18:06

原题:试编写一个函数,将字符串sub插入到字符串str中的第pos个位置,假设空间足够,函数原型为:void insert(char *str,char *sub,int pos)(不能用库函数)。

#include<iostream.h>#define SIZE 100//字符串预定义大小void InsertSubStr(char *str,char *sub,int pos){//将字符串sub插入到字符串str的第pos个位置,假设空间足够int len_str=0,len_sub=0,i;char *p=str;while(*p++!='\0')len_str++;//求主串长度p=sub;while(*p++!='\0')len_sub++;//求子串长度for(i=len_str;i>=pos;i--){//将串str中第pos个字符开始向后移len_sub个字符str[i+len_sub]=str[i];}//将sub的字符依次复制到str的从pos个字符到pos+len_sub-1个字符for(i=0;i<len_sub;i++){str[i+pos]=sub[i];}cout<<str<<endl;//输出结果}void main(){char str[SIZE],sub[SIZE];int pos;cout<<"请输入主串:";cin.getline(str,SIZE);cout<<endl;cout<<"请输入子串:";cin.getline(sub,SIZE);cout<<endl;cout<<"请输入插入位置:";cin>>pos;cout<<endl;InsertSubStr(str,sub,pos);cout<<endl;}