如何使用 C# 隨機生成一個字串?


首先,設定一個字串。

StringBuilder str = new StringBuilder();

使用 Random。

Random random = new Random((int)DateTime.Now.Ticks);

現在迴圈一個數字,該數字是所需隨機字串的長度。

for (int i = 0; i < 4; i++) {
   c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
   str.Append(c);
}

在上述每次迭代中,生成一個隨機字元並附加到字串中。

以下是一個完整的示例 -

示例

 互動演示

using System.Text;
using System;
class Program {
   static void Main() {
      StringBuilder str = new StringBuilder();
      char c;
      Random random = new Random((int)DateTime.Now.Ticks);
      for (int i = 0; i < 4; i++) {
         c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
         str.Append(c);
      }
      Console.WriteLine(str.ToString());
   }
}

輸出

ATTS

更新於: 22-Jun-2020

537 次瀏覽

開啟您的 事業

完成課程並獲得認證

立刻開始
廣告
© . All rights reserved.