利用栈数据结构倒序输出字符串

本文介绍了一种使用栈结构来实现字符串倒序的方法,通过遍历字符串,利用栈的后进先出特性,实现了字符串中每个单词的倒序输出。文章详细展示了如何使用C++中的标准库函数如islower、isupper和isspace进行字符类型判断,并通过栈将单词压入再弹出以达到倒序效果。

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

  1. 使用栈结构完成字符串的倒序,。
  2. 使用islower,isupper,isalpha等函数完成相关的大小写判断
#include<iostream>
#include<string>
#include<stack>
using namespace std;
string trans(string s, int n) {
	// write code here
	stack<string> line;
	string word;
	for (auto &temp : s) {
		if (isspace(temp)) {
			if (!word.empty())
				line.push(word);
			line.push(" ");
			word.clear();
		}
		else if (isalpha(temp)) {//判断如果是字母
			if (islower(temp))
				temp = toupper(temp);
			else if (isupper(temp))
				temp = tolower(temp);
			word += temp;
		}
	}
	line.push(word);//这句话很关键,如果字符的结尾没有空格的话,要把最后一个单词进栈。
	string result,top_str;
	while (!line.empty()) {    //出栈操作
		top_str = line.top();
		result = result + top_str;
		line.pop();
	}
	return result;
}
int main() {
	string a{ "hello world" };
	cout<<trans(a, 12);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值