假如有一列字符串“Henry Qi Hello World",通过函数转换成"World Hello Qi Henry".如何实现呢?
谢了如下代码,请各位朋友指正:
#include "iostream.h"
#include "string.h"
#include <stdlib.h>
void Reverse(char *dest);
void main()
{
//Get Reverse string
char *reverseSrc = "hello world Henry qi";
Reverse(reverseSrc);
}
void Reverse(char *dest)
{
char *pTemp = dest;
int count = -1;
int len = 0; //word length
int start = 0; //word start position
int end = 0; //word end position
char *p[4];
for(size_t i=0; i<strlen(pTemp); i++)
{
if(*(pTemp+i) == ' ')
{
count++;
if(count == 0)
{
len = i - start;
}
else
{
len = i - start -1;
}
start = i; //current i is assigned as the next word start
end = start; //the next word start is the source string word end
p[count] = (char *)calloc(sizeof(char), len+1); //alloc memory
for(int j=0; j<len; j++)
{
p[count][len-j-1] = pTemp[--end];
}
//cout<<p[count]<<endl;
}
}
//the last word
len = strlen(pTemp) - start -1;
end = strlen(pTemp);
p[count+1] = (char *)calloc(sizeof(char), len+1);
for(int j=0; j<len; j++)
{
p[count+1][len-j-1] = pTemp[--end];
}
//cout<<p[count+1]<<endl;
for(int k=3; k>=0; k--)
{
cout<<p[k]<<" ";
}
cout<<endl;
//cout<<strlen(pTemp)<<endl;
//cout<<*pTemp<<endl;
//cout<<*(pTemp+1)<<endl;
}
本段程序还有很多不足之处,有待完善。
目前还没有实现:允许用户随便输入一段字符串,然后得到标题所示结果。
哪位朋友如果实现了,请不吝附上。我也会尽快完善。