C++实现字符串单词的倒序 char 实现

C++实现字符串单词的倒序

#include <iostream>
#include “string.h”
#include <stdlib.h>

using namespace std;

void Reverse(char *dest);

void main()
{
//Get Reverse string
char *reverseSrc = “hello world Henry qi ds fgsg ddd”;
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[100];

//for(size_t i=0; i<strlen(pTemp); i++)
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]<<” “;
}
}
//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=count +1; k>=0; k–)
{
cout<<p[k]<<” “;
}
cout<<endl;
//cout<<strlen(pTemp)<<endl;
//cout<<*pTemp<<endl;
//cout<<*(pTemp+1)<<endl;
}