字符串倒序重新排列

本文介绍了一种使用C++实现字符串反转的方法,将一个给定的字符串中的单词顺序进行反转,例如将HenryQiHelloWorld转换为WorldHelloQiHenry。代码中详细展示了如何逐个单词地反转并拼接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假如有一列字符串“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;
}

 

本段程序还有很多不足之处,有待完善。

目前还没有实现:允许用户随便输入一段字符串,然后得到标题所示结果。

哪位朋友如果实现了,请不吝附上。我也会尽快完善。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值