对于顺序变化,我会这样做:
- 将它们放在
Array 的单词中split(' ')
- 由
Random生成一个从0到长度为Array减5的随机值
- 把它们放在一个句子中,给一些空格。
VB版本+测试结果
(这可能是你更感兴趣的)
Imports System
Imports System.Text
Public Module Module1
Public Sub Main()
Dim str As String = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
Console.WriteLine(GrabRandSequence(str))
Console.WriteLine(GrabRandSequence(str))
Console.WriteLine(GrabRandSequence(str))
Console.ReadKey()
End Sub
Public Function GrabRandSequence(inputstr As String)
Try
Dim words As String() = inputstr.Split(New Char() {" "c})
Dim index As Integer
index = CInt(Math.Floor((words.Length - 5) * Rnd()))
Return [String].Join(" ", words, index, 5)
Catch e As Exception
Return e.ToString()
End Try
End Function
End Module
结果
C# 版本
string[] words = input.Split(' '); //Read 1.
int val = (new Random()).Next(0, words.Length - 5); //Read 2.
string result = string.Join(" ", words, val, 5); //Read 3. improved by Enigmativy's suggestion
额外尝试
对于随机变化,我会这样做:
- 清除所有不必要的字符(.等)
- 将它们放入
List LINQ split(' ')
- 通过
LINQ在其中选择Distinct(可选,避免出现Lorem Lorem Lorem Lorem Lorem这样的结果)
- 生成 5 个不同的随机值,从 0 到大小为
List 到 Random(在不明显时重复选择)
- 根据
List中的随机值选择单词
- 把它们放在一个句子中,给一些空格。
警告:这句话可能根本没有任何意义!!
C# 版本(仅限)
string input = "the input sentence, blabla";
input = input.Replace(",","").Replace(".",""); //Read 1. add as many replace as you want
List<string> words = input.Split(' ').Distinct.ToList(); //Read 2. and 3.
Random rand = new Random();
List<int> vals = new List<int>();
do { //Read 4.
int val = rand.Next(0, words.Count);
if (!vals.Contains(val))
vals.Add(val);
} while (vals.Count < 5);
string result = "";
for (int i = 0; i < 5; ++i)
result += words[vals[i]] + (i == 4 ? "" : " "); //read 5. and 6.
你的结果在result