欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2017年01月05日 16:26:18   作者:Yesi  
這篇文章主要給大家介紹了C#中倒序輸出字符串的方法示例,本文中的字符串倒序指的是將“嗎? 好 近 最”輸出“最 近 好 嗎?”,文中給出了兩種方法,需要的朋友可以參考借鑒,下面來跟著小編一起學(xué)習(xí)學(xué)習(xí)吧。

前言

本文將演示如何將字符串的單詞倒序輸出。注意:在這里我不是要將“John” 這樣的字符串倒序?yàn)槌伞皀hoJ”。這是不一樣的,因?yàn)樗耆剐蛄苏麄€(gè)字符串。而以下代碼將教你如何將“你 好 我是 緹娜”倒序輸出為“緹娜 是 我 好 你”。所以,字符串的最后一個(gè)詞成了第一個(gè)詞,而第一個(gè)詞成了最后一個(gè)詞。當(dāng)然你也可以說,以下代碼是從最后一個(gè)到第一個(gè)段落字符串的讀取。

對(duì)此我使用了兩種方法。

第一種方法僅僅采用拆分功能。

根據(jù)空格拆分字符串,然后將拆分結(jié)果存放在一個(gè)string類型的數(shù)組里面,將數(shù)組倒序后再根據(jù)索引打印該數(shù)組。

代碼如下

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("請(qǐng)輸入字符串:");
   Console.ForegroundColor = ConsoleColor.Yellow;
   string s = Console.ReadLine();
   string[] a = s.Split(' ');
   Array.Reverse(a);
   Console.ForegroundColor = ConsoleColor.Red;
   Console.WriteLine("倒序輸出結(jié)果為:");
   for (int i = 0; i <= a.Length - 1; i++)
   {
    Console.ForegroundColor = ConsoleColor.White;
    Console.Write(a[i] + "" + ' ');
   }
   Console.ReadKey();
  }
 }
}

輸出結(jié)果

第二種方法

我不再使用數(shù)組的倒序功能。我只根據(jù)空格拆分字符串后存放到一個(gè)數(shù)組中,然后從最后一個(gè)索引到初始索引打印該數(shù)組。

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("請(qǐng)輸入字符串:");
   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();
  }
 }
}

輸出結(jié)果

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家學(xué)習(xí)或者使用C#能帶來一定的幫助,如果有疑問大家可以留言交流。

相關(guān)文章

最新評(píng)論