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.
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.
Is there a way to avoid this error?
Aucun commentaire:
Enregistrer un commentaire