当前位置: 移动技术网 > IT编程>开发语言>c# > C#中倒序输出字符串的方法示例

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

前言

本文将演示如何将字符串的单词倒序输出。注意:在这里我不是要将“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();
  }
 }
}

输出结果

第二种方法

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

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#能带来一定的帮助,如果有疑问大家可以留言交流。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网