现在的位置: 首页 > 综合 > 正文

字符串处理算法(三)按指定位置交换字符串两部分的位置

2013年06月22日 ⁄ 综合 ⁄ 共 608字 ⁄ 字号 评论关闭

实现一个函数:按指定位置交换字符串两部分的位置

比如:函数输入("abcde", 2) 输出"cdeab"

题目的意思应该比较明白,代码实现如下:

int SwapStr(char* input, int pos)
{
	char* p = input+pos;
	int nLen = strlen(input);

	//对输入数据检查
	if (input==NULL || nLen<pos)
	{
		return -1;
	}

	char* temp= new char[pos+1];

	if (temp == NULL) return -1;

	memcpy(temp, input, pos);
	temp[pos]='\0';
	memcpy(input, p, nLen-pos);
	memcpy(input+nLen-pos, temp, pos);

	delete[] temp;
	temp = NULL;

	return 0;
}
int main()
{
	char* str=new char[10];//想想这里为什么不是char* str="abcde";或者直接SwapStr("abcde",2);
	strcpy(str, "abcde");
	cout << str << endl;

	SwapStr(str, 2);

	cout << str << endl;

	delete[] str;

	return 0;
}

测试结果:

abcde
cdeab


转载请注明原创链接:http://blog.csdn.net/wujunokay/article/details/12067631

抱歉!评论已关闭.