以单词为单位反转字符串,要求不申请任何空间

问题描述:

存在一个可读写的字符串,其中包括若干单词,单词间以空格区分,要求以单词为单位对字符串进行反转。

 

算法思想:

(1)利用异或运算可以不申请空间进行字符交换

(2)利用递归的思想

(3)使用strchr函数区分单词

 

解决方案:

include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include<iostream>
using namespace std;
 

void recursive_swap_char(char* lhs, char* rhs)// Using recursive to swap char.
{
 if(rhs <= lhs)
  return;

 *lhs ^= *rhs;
 *rhs ^= *lhs;
 *lhs ^= *rhs;
 
 recursive_swap_char(lhs + 1, rhs - 1);
}


void recursive_word_reverse(char* cur, char* next)// Using recursive to reverse chars of word
{
 // If this is the last word, reverse as a string
 if(next == NULL)
 {
  recursive_swap_char(cur, cur + strlen(cur) - 1);
  return;
 }

 // Reverse char within current word
 recursive_swap_char(cur, next - 1);

 // Reverse next word
 recursive_word_reverse(next + 1, strchr(next + 1, ' '));
}

char* reverse_by_word(char* src)
{
 // If only one word, return directly
 if(strchr(src, ' ') == NULL)
  return src;

 // Reverse whole string
 recursive_swap_char(src, src + strlen(src) - 1);

 // Reverse word
 recursive_word_reverse(src, strchr(src, ' '));

 return src;
}

void print(char* src)
{
 cout << "src:    " << src << endl;
 cout << "dest:   " << reverse_by_word(src) << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
 char one[] = "one";
 char one_two[] = "one two";
 char one_two_three[] = "one two three";
 char one_two_three_four[] = "one two three four";
 char str_for_test[] = "There is a program for test";
 
 print(one);
 print(one_two);
 print(one_two_three);
 print(one_two_three_four);
 print(str_for_test);

 getchar();
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值