【问题标题】:How to populate a text file in C#如何在 C# 中填充文本文件
【发布时间】:2022-01-21 12:43:16
【问题描述】:

用 C# 填充文本文件的程序

我正在尝试使用随机函数生成随机字符串并将它们添加到文件中。但它会一遍又一遍地重复相同的字符串。

需要有关如何做到这一点的想法。

string va = "2346789ABCDEFGHJKLMNPQRTUVWXYZabcdefghjkmnpqrtuvwxyz";
        Random ran = new Random();
        string[] txt = new string[] {};
        
        for (int i = 0; i < 25; i++)
        {
            while (txt.Length < 8)
            {
                txt[i]= va[0 .. ran.Next()];
            }
        }
        for (int i = 0; i < txt.Length; i++) {
            File.AppendAllText($"Externalfiles/{Exfile}", txt[I]);

我正在寻找一个只使用字符串和随机的函数。 并给出多个随机字符串。

我的程序需要一个迭代循环,它本身为每次迭代提供一个新字符串,以便我可以将这些字符串直接添加到文件中。

其他方法也值得赞赏。 :))

【问题讨论】:

  • 我想while应该是while (txt[i].Length &lt; 8)(但要注意,它以null开头,所以首先初始化为空字符串)。此外,您可能希望在该文本中添加txt[i] += va...
  • 这能回答你的问题吗? How can I generate random alphanumeric strings?
  • “我正在尝试使用随机函数”,另外,“但它不断重复相同的字符串。” --> 将您的随机实例移出函数并进入类。请参阅下面 tuncaycemuzun 的答案。问题是,如果您快速连续调用该函数,那么它将在后续调用中使用相同的基于时间的种子,并为您提供相同的“随机”字符。将您的 Random 实例移到类级别并重新使用它可以消除此问题。

标签: c# string random file-handling


【解决方案1】:

使用 UniqueRandom 类,您可以根据字符串的长度创建一系列数字,并且生成索引的任何字符串字符都将从 UniqueRandom 类中删除。

class UniqueRandom
{
    private readonly List<int> _currentList;
    private readonly Random _random = new Random();

    public UniqueRandom(IEnumerable<int> seed)
    {
       _currentList = new List<int>(seed);
    }

    public int Next()
    {
       if (_currentList.Count == 0)
       {
          throw new ApplicationException("No more numbers");
       }

       int i = _random.Next(_currentList.Count);
       int result = _currentList[i];
       _currentList.RemoveAt(i);
       return result;
    }
    public bool IsEmpty
    {
       get
       {
          return _currentList.Count == 0;
       }
    }
}

现在使用

string va = "2346789ABCDEFGHJKLMNPQRTUVWXYZabcdefghjkmnpqrtuvwxyz";
UniqueRandom u = new UniqueRandom(Enumerable.Range(0, va.Length - 1));

while (!u.IsEmpty)
{
    string txt = string.Empty;
    while(txt.Length < 8)
    {
        if (u.IsEmpty)
          break;
        int select = u.Next();
        txt += va[select];
    }
    File.AppendAllText($"Externalfiles/{Exfile}", txt);
}

【讨论】:

  • 您在循环中调用CreateRandomText()。由于您的函数在其中创建了一个 Random 实例,因此您将获得重复的字符,因为它使用时间作为种子。将 Random 移出 CLASS 级别。
  • 我没有注意到单词中不应出现重复字符。我编辑了答案
  • 很可能在循环中存在足够的延迟,因为它正在写入文件。如果使用不同,旧版本可能会失败。新版本看起来好多了!
【解决方案2】:

您可以使用以下函数来创建随机字符串。

private static Random random = new Random();

public static string RandomString(int length)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return new string(Enumerable.Repeat(chars, length)
        .Select(s => s[random.Next(s.Length)]).ToArray());
}

How can I generate random alphanumeric strings?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    相关资源
    最近更新 更多