我想在字符串的随机部分插入随机数量的点(从 1 到 7)而不破坏布局。
这是我当前的代码:
Random rand = new Random();
string[] words = iTemplate.Text.Split(' ');
string result = string.Empty;
for (int i = 0; i < words.Count(); i++)
{
string word = words[i];
if (rand.Next(i, words.Count()) == i)
{
for (int dots = rand.Next(1, 7); dots > 0; dots--)
word += ".";
}
result += word + " ";
}
有没有更有效或更好的 LINQ 选项?
现在,由于它是随机的,可能会出现没有点出现的情况。我通过使用if (rand.Next(i, words.Count()) == i)
which 似乎可以工作来缩小范围,但仍然有一些结果只显示 1 到 3 个插入点的地方。
我如何保证在此过程中点至少插入 4 个不同的位置?
根据评论请求的示例数据/结果:
string template = "Hi, this is a template with several words on it and I want to place random dots on 4 different random places every time I run the function";
结果1:
string result = "Hi, this... is a template with several.. words on it and. I want to place random dots on 4 different random...... places every time I run the function";
结果 2:
string result = "Hi, this is a template. with several... words on it and I want to..... place random dots on 4 different random. places every time I run the function";
结果 3:
string result = "Hi, this. is a template with... several words on it and I want to place random.. dots on 4 different random....... places every time I run the.. function";