コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】文字列を時計回りに回転する関数

ソースコード

private static string RotateClockwise( string input, int count )
{
    for ( var i = 0; i < count; i++ )
    {
        input = RotateClockwise( input );
    }

    return input;
}

private static string RotateClockwise( string input )
{
    var lines    = input.Split( '\n', StringSplitOptions.RemoveEmptyEntries );
    var rowCount = lines.Length;
    var colCount = lines[ 0 ].Length;

    var matrix = new char[ rowCount, colCount ];

    for ( var i = 0; i < rowCount; i++ )
    {
        for ( var j = 0; j < colCount; j++ )
        {
            matrix[ i, j ] = lines[ i ][ j ];
        }
    }

    var rotatedMatrix = new char[ colCount, rowCount ];

    for ( var i = 0; i < colCount; i++ )
    {
        for ( var j = 0; j < rowCount; j++ )
        {
            rotatedMatrix[ i, j ] = matrix[ rowCount - j - 1, i ];
        }
    }

    var rotatedBuilder = new StringBuilder();
    for ( var i = 0; i < colCount; i++ )
    {
        for ( var j = 0; j < rowCount; j++ )
        {
            rotatedBuilder.Append( rotatedMatrix[ i, j ] );
        }

        if ( i != colCount - 1 )
        {
            rotatedBuilder.Append( "\n" );
        }
    }

    return rotatedBuilder.ToString();
}

使用例

var str = @"1000
1111";

Debug.LogWarning( RotateClockwise( str ) );
Debug.LogWarning( RotateClockwise( str, 1 ) );
Debug.LogWarning( RotateClockwise( str, 2 ) );
Debug.LogWarning( RotateClockwise( str, 3 ) );
Debug.LogWarning( RotateClockwise( str, 4 ) );