翻转单词单词顺序 C/C++实现

  • Post author:
  • Post category:其他




要求:将一个英文语句以单词为单位逆序排放。

例如“I am a boy”,逆序排放后为“boy a am I”所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符

  • 解法1:
#include <string>
#include <iostream>

using namespace std;
void reverse(char *begin, char *end )
{
    if(begin && end)
    {
        while(begin<end)
        {
			char tmp = *begin;
            *begin++ = *end;
			*end-- = tmp;
        }
    }
    return;
}

char* sentenceReverse(char *str)
{
    char* begin = str;
    char *end = str;
    while(*end != '\0')
        end++;
	end--;
    
    /* first reverse all */
    reverse(begin, end);
    
    /* reverse every world */
    begin = end = str;
    while(*begin != '\0')
    {
        if(*end == ' ' || *end == '\0')
        {
            reverse(begin, --end);
			++end;
            begin = ++end;
        }
        else
        {
            ++end;
        }
        
    }
	return str;
}

int main()
{
	std::string str;
	getline(std::cin,str);
	//str = "am i a boy";
	std::cout<<sentenceReverse(const_cast<char*>(str.c_str()));
}
  • 解法2:
#include <string>
#include <iostream>
#include <stack>

using namespace std;

char* sentenceReverse(char *str)
{
	std::stack<char> first;
	std::stack<char> second;
	char *head = str;
	while(*head != '\0')
	{
		if( *head == ' ')
		{
			while(first.size()>0)
			{
				second.push(first.top());
				first.pop();
			}
			second.push(*head);
		}
		else
		{
			first.push(*head);
		}
		head++;
	}
	/* do last */
	while(first.size()>0)
	{
		second.push(first.top());
		first.pop();
	}

	head = str;
	while(second.size()>0)
	{
		*head = second.top();
		second.pop();
		head++;
	}
	return str;
}

int main()
{
	std::string str;
	getline(std::cin,str);
	//str = "am i a boy";
	std::cout<<sentenceReverse(const_cast<char*>(str.c_str()));
}
  • 解法3:
#include <string>
#include <iostream>

using namespace std;

string sentenceReverse(std::string &str)
{
	int length = str.length();
	int head = 0;
	int tail = length;
	string tmp = str;
	str = "";
	while(tail > 0)
	{
		if( std::string::npos!= (tail = tmp.rfind(' ')))
		{
			str =str + tmp.substr(tail+1,length)+" ";
			tmp = tmp.substr(head,tail);
		}
	}
	str+=tmp;
	return str;
}

int main()
{
	std::string str;
	getline(std::cin,str);
	//str = "am i a boy";
	std::cout<<sentenceReverse( str);
}



版权声明:本文为u013340341原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。