介紹
在本文中,我将示範如何将字元串的單詞倒序輸出。在這裡我不是要将“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();
}
}
}