面试小题:反转句子.

最近看一些面经的题目.有这样一个题目:
反转句子.但要以逗号作为分隔.样例如下:
“hello world, god bless you” -> “world hello, you bless god”
觉得很有用.自己试着做了下.

代码:

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


int main(void){
    
    
	string str = "hello world, god bless you"; //world hello, you bless god
	string res;
	stack<string>s;//因为逆序串输出.所以栈刚好符合特点.
	string temp;
	for (int i = 0; i < str.size(); i++) {
    
    
		if (str[i] != ','&&str[i]!=' ') {
    
    //判断是不是字母.
			temp += str[i];
		}
		else if (str[i]==' ') {
    
    //判断是不是到了空格.是则表示已经有了一个完整的单词
			s.push(temp);
			s.push(" ");//要加入空格 因为空格也算空字符串
			temp.clear();
		}
		else if (str[i] == ',') {
    
    //当为','的时候表示stack中已经有一个完整的字符串.直接加到结果中
			s.push(temp);
			temp.clear();
			while (!s.empty()) {
    
    
				res += s.top();
				s.pop();
			}
			res += ",";
		}
	}
	s.push(temp);//因为最后没有判断的东西 所以需要手动加入栈中
	temp.clear();
	while (!s.empty()) {
    
    
		res += s.top();
		s.pop();
	}
	cout << res;
}



在这里插入图片描述
//上面为参考.没有考虑其他的例子.可能会有很多种可能.

猜你喜欢

转载自blog.csdn.net/qq_43507406/article/details/114788062