实现一个函数:按指定位置交换字符串两部分的位置
测试结果:
比如:函数输入("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;
}
测试结果:

本文介绍了一种C++方法,用于根据指定位置交换字符串的前后两部分,例如输入"abcde"和2,输出将为"cdeab"。此功能在笔试和面试中可能作为算法问题出现。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



