コガネブログ

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

【C#】パスワードのようなランダムな文字列を生成して返す関数

ソースコード

public static class StringUtils
{
    private const string PASSWORD_CHARS = 
        "0123456789abcdefghijklmnopqrstuvwxyz";

    public static string GeneratePassword( int length )
    {
        var sb  = new System.Text.StringBuilder( length );
        var r   = new System.Random();

        for ( int i = 0; i < length; i++ )
        {
            int     pos = r.Next( PASSWORD_CHARS.Length );
            char    c   = PASSWORD_CHARS[ pos ];
            sb.Append( c );
        }

        return sb.ToString();
    }
}

使い方

Debug.Log( StringUtils.GeneratePassword( 4 ) );
Debug.Log( StringUtils.GeneratePassword( 8 ) );

参考サイト様

関連記事