插入字符串

该博客介绍了如何编写一个函数,将指定子字符串sub插入到字符串str的特定位置pos,探讨了算法实现细节,确保在空间足够的前提下完成操作。
摘要由CSDN通过智能技术生成

原题:试编写一个函数,将字符串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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Storm-Shadow

你的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值