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

 輸出結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM