C#字符串的倒序输出
介绍
在本文中,我将演示如何将字符串的单词倒序输出。在这里我不是要将“John” 这样的字符串倒序为成“nhoJ”,。这是不一样的,因为它完全倒序了整个字符串。而以下代码将教你如何将“你 好 我是 缇娜”倒序输出为“缇娜 是 我 好 你”。所以,字符串的最后一个词成了第一个词,而第一个词成了最后一个词。当然你也可以说,以下代码是从最后一个到第一个段落字符串的读取。
对此我使用了两种方法。第一种方法仅仅采用拆分功能。根据空格拆分字符串,然后将拆分结果存放在一个string类型的数组里面,将数组倒序后再根据索引打印该数组。
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 将字符串的单词倒序输出 { class Program { static void Main( string [] args) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine( "请输入字符串:" ); Console.ForegroundColor = ConsoleColor.Yellow; string s = Console.ReadLine(); string [] a = s.Split( ' ' ); Array.Reverse(a); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine( "倒序输出结果为:" ); for ( int i = 0; i <= a.Length - 1; i++) { Console.ForegroundColor = ConsoleColor.White; Console.Write(a[i] + "" + ' ' ); } Console.ReadKey(); } } } |
输出结果
对于第二种方法,我不再使用数组的倒序功能。我只根据空格拆分字符串后存放到一个数组中,然后从最后一个索引到初始索引打印该数组。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 将字符串的单词倒序输出 { class Program { static void Main( string [] args) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine( "请输入字符串:" ); Console.ForegroundColor = ConsoleColor.Yellow; int temp; string s = Console.ReadLine(); string [] a = s.Split( ' ' ); int k = a.Length - 1; temp = k; for ( int i = k; temp >= 0; k--) { Console.Write(a[temp] + "" + ' ' ); --temp; } Console.ReadKey(); } } } |
输出结果
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)