C++ 从指定位置开始,删除指定长度的字符串

1:先检查指定位置和指定长度的合法性;

2:找到指定位置;

3:删除指定长度个字符串。

具体代码如下:

#include <iostream>
using namespace std;

char *GetCharsDeleted(char *str,int pos,int len)
{
	char *p=str+pos-1;
	int i=0;
	char *temp=NULL;
	int ls=strlen(str);//计算字符长度
	
	if(pos<1 || (p-str)>ls)//检查pos是否大于1,
	{						//或者是否超出字符串长度
		cout<<"pos error!"<<endl;
		exit(1);
	}
	char *end=str;
	while(*end++);
	if((p+len-str) >=ls)
	{
		temp=new char[end-p-1];
		while(*p!='\0')
		temp[i++]=*p++;
	}
	
	if(*p && *(p+len))
	{
		temp=new char[len];
		while(len--)
		{
			temp[i++]=*p++;
		}	
	}
	return temp;
}

char *deleteChars(char *str,int pos,int len)
{
	char *p=str+pos-1;//p指向pos位置的字符
	int ls=strlen(str);//计算字符长度

	if(pos<1 || (p-str)>ls)//检查pos是否大于1,
	{						//或者是否超出字符串长度	
		return str;
	}
	if((p+len-str)>=ls)//len大于pos后剩余的字符个数
					// 只需对pos位置赋‘\0’
	{
		*p='\0';

		return str;
	}
	
	//当len小于pos位置后的字符个数时,进行删除操作
	while(*p && *(p+len))
	{
		*p=*(p+len);
		p++;
	}
	*p='\0';

	return str;
}

int main()
{
	char str[]="Welcome to here;";
	int pos=0;
	int len=0;
	cout<<"string: "<<str<<endl;
	cout<<"please input pos:";
	cin>>pos;
	cout<<"please input len:";
	cin>>len;
	cout<<"delete chars :"<<GetCharsDeleted(str,pos,len)<<endl;
	deleteChars(str,pos,len);
	cout<<"after delete :"<<str<<endl;
return 0;
}
GetCharsDeleted函数用来输出将要被删除的字符串;

deleteChars函数用来删除指定字符串。

猜你喜欢

转载自blog.csdn.net/qq_35965090/article/details/77104247