alunote’s blog

C#,SQL,JavaScriptなどの技術メモをゆっくり投稿しています。

【C#】文字列を逆並び変換する

今回は、文字列を逆並び変換する方法について記述します。

◆逆並び変換
拡張メソッドを使用することで、文字列を簡単に逆並び変換することが可能です。
今回は逆並び変換なのでReverseを使用します。

◆逆並び変換のソースコード

using System;
//↓Reverseを使用するため
using System.Linq;

class Task_9
{
    public static void Main()
    {
        string text1 = "abc";
        string text2 = "123";

        //文字列を逆並び変換
        Console.WriteLine("▼文字列(string)を逆並びに変換する。");
        Console.WriteLine("変換前:" + text1 + ",\t変換後:" + string.Concat(text1.Reverse()));
        Console.WriteLine("変換前:" + text2 + ",\t変換後:" + string.Concat(text2.Reverse()));
    }
}

◆逆並び変換の実行結果
f:id:alunote:20181004143531p:plain

★おまけ
Reverseで遊んでみたいと思います。
敵の敵は味方だ!」という感じに「逆並びの逆並びは同じだ!」ということを実証したいと思います。

◆おまけのソースコード

using System;
using System.Linq;

class Task_9
{
    public static void Main()
    {
        // 元データ
        string text1 = "あいうえお";
        // 変換1回目データ
        string reverseText1 = string.Concat(text1.Reverse());
        // 変換2回目データ
        string reverseText2 = string.Concat(reverseText1.Reverse());

        Console.WriteLine("変換前:" + text1);
        Console.WriteLine("変換1回目:" + reverseText1);
        Console.WriteLine("変換2回目:" + reverseText2);
        Console.Write("結果:");
        if (text1 == reverseText2)
        {
            Console.WriteLine("同じ!");
        }else{
            Console.WriteLine("違う!");
        }
    }
}

◆おまけの実行結果
f:id:alunote:20181004143522p:plain

。。。語るまでもなく同じです。

以上です。
この記事が誰かの役に立つことを祈ります。