我正在寻找从字符串中获取一定数量单词(按顺序)的最有效方法.
所以,假设我有一段文字:
"Lorem Ipsum只是印刷和排版行业的虚拟文本.自16世纪以来,Lorem Ipsum一直是业界标准的虚拟文本,当时一个未知的打印机拿了一个类型的厨房并乱扰它制作一个类型的样本书.它幸存了下来不仅五个世纪,而且电子排版的飞跃,基本保持不变.它在20世纪60年代推出了包含Lorem Ipsum通道的Letraset表,以及最近使用包括Lorem Ipsum版本在内的桌面出版软件Aldus PageMaker. "
我希望能够在段落中的随机位置抓取可变数量的单词.因此,如果需要5个单词,则某些输出的示例可以是:
"释放Letraset表包含"
"Lorem Ipsum简直就是假的"
"只有五个世纪,但也"
这样做的最佳方式是什么?
用空格分割数据以获得单词列表,然后找到一个随机位置来选择单词(从结尾起至少5个单词),然后将单词重新连接在一起.
private static readonly Random random = new Random(); public static void Main(string[] args) { var data = "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(GetRandomWords(data, 5)); Console.ReadLine(); } private static string GetRandomWords(string data, int x) { // Split data into words. var words = data.Split(' '); // Find a random place to start, at least x words back. var start = random.Next(0, words.Length - x); // Select the words. var selectedWords = words.Skip(start).Take(x); return string.Join(" ", selectedWords); }
示例输出:
the 1960s with the release PageMaker including versions of Lorem since the 1500s, when an leap into electronic typesetting, remaining typesetting, remaining essentially unchanged. It