C 实现字符串翻转(单词不翻转)

Tony is a cute student  =>  tneduts etuc a si ynoT =>  student cute a is Tony

思路: 1>翻转整个字符串    2>再把单个单词进行翻转

 

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

void reversalFunc(char * ch, int start, int end)
{
	if (start >= end ||  end == 0)
	{
		return;
	}
	char temp = 0;
	while(start < end)
	{
		temp = ch[start];
		ch[start] = ch[end];
		ch[end] = temp;
		++start;
		--end;
	}

}
int main()
{
	char  ch[] = "Tony is a cute student";
	//全部翻转
	reversalFunc(ch, 0, strlen(ch) - 1);
	//单词翻转

	int start = 0;
	for (int i = 0; i <= strlen(ch); i++)
	{
		if (ch[i] == ' ' || ch[i] == '\0')
		{
			reversalFunc(ch, start, i-1);
			start = i + 1;
		}
	}

	cout << ch << endl;
	return 0;
}

  最近学习了一下STL,刷题的时候又遇到了这个,写了下面这种

#include <iostream>
#include <vector>
#include <string>
using namespace std;

string reverse(string sentence)
{
	int start = 0, end = 0;
	vector<string> vt;
	string resultStr;
	while (end <= sentence.size())
	{
		if (sentence[end] == ' ' || end == sentence.size())
		{
			
			vt.push_back(sentence.substr(start, end - start));
			start = end + 1;
		}

		end++;
	}

	for (vector<string>::reverse_iterator it = vt.rbegin(); it != vt.rend(); ++it)
	{
		resultStr.append(*it);
		resultStr.append(" ");
	}

	return resultStr;
	
}

int main()
{
	string str;
	getline(cin, str);
	cout << reverse(str) << endl;
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值