求大神指点“关于字符串中字符的交换,程序运行结果为什么没有实现?”
求大神指导“关于字符串中字符的交换,程序运行结果为什么没有实现?”
------解决方案--------------------
很简单,你交换的时候for循环只能进行到一半的位置(这时前半部分和后半部分已经交换了)。如果你循环继续下去,字符又给交换回原来的位置了。跟踪一下吧
------解决方案--------------------
又是一个交换了两次的问题。
j从0递增到len,从0递增到中间时已经交换一次了,再从中间递增到len,又换所有的换回来了
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void Encrypt(char*);
int main()
{
char string[] = "efvrg";
int length;
length = strlen(string);
if(length == 5)
{
Encrypt(string);
}
else
cout<<"Input Error."<<endl;
cout<<endl;
return 0;
}
void Encrypt(char* string)
{
int len = strlen(string);
for(int i=0; i<len; i++)
{
int n = 0;
n = string[i]*2 + 10;
string[i] = (int)string[i]*2 + 10;
if(n >= 128)
{
n = n/3;
cout<<setw(2)<<(char)n<<endl;
string[i] = char(n);
}
else
{
cout<<setw(2)<<(char)n<<endl;
string[i] = (char)n;
}
}
cout<<endl;
for(int k1=0; k1<len; k1++)
cout<<setw(2)<<string[k1];
cout<<endl;
int j;
char temp;
for(j=0; j<len; j++)
{
temp = string[j];
string[j] = string[len-j-1];//为什么这里的交换没有真正实现呀?!!!!!!!!!!!
string[len-j-1] = temp;
}
for(j=0; j<len; j++)
cout<<setw(2)<<string[j];
}
------解决方案--------------------
很简单,你交换的时候for循环只能进行到一半的位置(这时前半部分和后半部分已经交换了)。如果你循环继续下去,字符又给交换回原来的位置了。跟踪一下吧
------解决方案--------------------
又是一个交换了两次的问题。
j从0递增到len,从0递增到中间时已经交换一次了,再从中间递增到len,又换所有的换回来了