C#中倒序输出字符串的方法示例

作者:Yesi 时间:2023-10-27 21:45:13 

前言

本文将演示如何将字符串的单词倒序输出。注意:在这里我不是要将“John” 这样的字符串倒序为成“nhoJ”。这是不一样的,因为它完全倒序了整个字符串。而以下代码将教你如何将“你 好 我是 缇娜”倒序输出为“缇娜 是 我 好 你”。所以,字符串的最后一个词成了第一个词,而第一个词成了最后一个词。当然你也可以说,以下代码是从最后一个到第一个段落字符串的读取。

对此我使用了两种方法。

第一种方法仅仅采用拆分功能。

根据空格拆分字符串,然后将拆分结果存放在一个string类型的数组里面,将数组倒序后再根据索引打印该数组。

代码如下


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();
 }
}
}

输出结果

C#中倒序输出字符串的方法示例

第二种方法

我不再使用数组的倒序功能。我只根据空格拆分字符串后存放到一个数组中,然后从最后一个索引到初始索引打印该数组。


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();
 }
}
}

输出结果

C#中倒序输出字符串的方法示例

来源:http://www.cnblogs.com/Yesi/p/5875031.html

标签:c#,字符串,倒序
0
投稿

猜你喜欢

  • jmeter+ant+jenkins自动化测试环境配置搭建过程

    2023-11-17 23:38:06
  • spring cloud将spring boot服务注册到Eureka Server上的方法

    2023-12-08 19:42:09
  • Android AlertDialog(对话框)实例详解

    2023-07-19 11:37:55
  • Android Button 自带阴影效果另一种解决办法

    2021-06-07 04:23:02
  • Android开发之SD卡文件操作分析

    2022-01-09 04:55:16
  • 详解java_ 集合综合案例:斗地主

    2022-02-08 04:14:49
  • Java字符串驼峰与下换线格式转换如何实现

    2022-02-18 09:56:14
  • Spring中的注解@Autowired实现过程全解(@Autowired 背后的故事)

    2023-01-01 06:02:53
  • Java 常量池的实例详解

    2023-12-04 00:51:28
  • 关于Java虚拟机HotSpot

    2022-10-28 18:36:01
  • CentOS 7下JDK8的详细安装步骤

    2022-02-18 12:06:28
  • C#控制台输出进度和百分比的实例代码

    2021-10-01 23:49:43
  • Java 根据某个 key 加锁的实现方式

    2023-10-27 07:54:20
  • Go Java算法之找不同示例详解

    2021-10-29 19:37:08
  • C#通过html调用WinForm的方法

    2022-02-26 03:53:16
  • Android中bindService基本使用方法概述

    2023-08-05 19:18:56
  • Android 列表形式的切换的示例代码

    2022-12-17 07:38:24
  • 一篇文章带你搞定JAVA反射

    2023-09-18 02:27:51
  • Android桌面插件App Widget用法分析

    2022-02-05 02:26:39
  • C#实现DataTable转TXT、CSV文件

    2022-08-09 06:50:09
  • asp之家 软件编程 m.aspxhome.com