C#中倒序輸入字符串的辦法示例。本站提示廣大學習愛好者:(C#中倒序輸入字符串的辦法示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中倒序輸入字符串的辦法示例正文
前言
本文將演示如何將字符串的單詞倒序輸入。留意:在這裡我不是要將“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#能帶來一定的協助,假如有疑問大家可以留言交流。