I am searching for the most efficient way to grab a set amount of words (in order) from a string.
So let's say I have a paragraph of text:
"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."
I want to be able to grab a variable amount of words at random positions in the paragraph. So if 5 words were wanted an example of some outputs could be:
What would be the best way of going about doing this?
Split the data up by spaces to get a list of words, then find a random place to select the words from (at least 5 words from the end), and then join the words back together.
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);
}
Example output:
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments