简体   繁体   English

C# 随机拆分字符串

[英]C# Splitting strings randomly

I have a string like this:我有一个这样的字符串:

string str = "ABCDEFGHI"

I want a result like:我想要这样的结果:

string str1 = "AB";
string str2 = "CDEF";
string str3 = "G";
string str4 = "HI";

The idea is to randomly partitioning a string into a sequence of substring with random length.这个想法是将一个字符串随机划分为一个随机长度的 substring 序列。

I've tried the following:我试过以下方法:

public static string SplitString(string input)
    {
        string result = "";
        int j = 0;
        for (int i = 0; i < input.Length; i++)
        {
            Random random = new Random();
            j = random.Next(i+1, input.Length);
            string subString = input.Substring(i,j); //ERROR
            i = j-1;
            Console.WriteLine("New substring: " + subString);
            result = result + subString;
        }
        return result;
    }

It looks like this approach is not correct at all, because when I create a substring and the i index is greater than the j , the program goes in exception.看起来这种方法根本不正确,因为当我创建一个 substring 并且i索引大于j时,程序会出现异常。

Is there a way to avoid this error?有没有办法避免这个错误?

Substring(Int32, Int32) extracts a substring of length j starting from index i, which will break once i+j >= input.Length - i is true. Substring(Int32, Int32) 从索引 i 开始提取长度为 j 的 substring,一旦 i+j >= input.Length - i 为真,它将中断。

Example: Substring(2,2) applied to "ABCDEF" should return "CD".示例:应用于“ABCDEF”的 Substring(2,2) 应返回“CD”。 In your specific case it would be possible to have something like Substring(4,5) throwing an Exception since the String does not have enough elements.在您的特定情况下,可能会有像 Substring(4,5) 这样的东西抛出异常,因为 String 没有足够的元素。 At some point this loop will always cause an exception.在某些时候,这个循环总是会导致异常。

More details on the use of Substring can be found here: https://learn.microsoft.com/en-us/do.net/api/system.string.substring?view.netcore-3.1有关 Substring 使用的更多详细信息,请参见此处: https://learn.microsoft.com/en-us/do.net/api/system.string.substring?view.netcore-3.1

Some things you can fix:您可以解决的一些问题:

  • Generate a random number in 1 to input.Length - i instead of 1 to input.Length生成一个随机数 in 1 to input.Length - i 而不是 1 to input.Length
  • Set i = i + j - 1 instead of i = j - 1设置 i = i + j - 1 而不是 i = j - 1

Algorithm:算法:

  1. Step
  • i = 0我 = 0
  • Randomly roll j in 0 to (input.Length-1)随机滚动 j in 0 到 (input.Length-1)
  • Output j first letters starting from index i. Output j 从索引 i 开始的第一个字母。
  • Set i = i + j - 1设 i = i + j - 1
  1. Step
  • i = j我 = j
  • Randomly roll j in 0 to (input.Length-1 - i)在 0 中随机滚动 j 到 (input.Length-1 - i)
  • Output j first letters starting from index i. Output j 从索引 i 开始的第一个字母。
  • Set i = i + j - 1设 i = i + j - 1
  1. Continue继续

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM