Random
paragraphsIt is possible to generate random paragraphs and sentences. The text must look like regular English writing. A C# method can generate language that appears natural.
This code can be used for testing or debugging purposes. It is also an interesting exercise in how to create random sequences of data.
This class
contains the logic for the random text generator. It has an AddContentParagraphs
method. And we can fetch the resulting string
from the Content property.
Random
instance's Next method. It adds the paragraph. After the paragraph, it inserts 2 line breaks.AddParagraph
method calls AddSentence
once per each sentence required.AddSentence
iterates up to the word count. It randomly selects each word from the words array and appends it.RandomText
class
, and then call AddContentParagraphs
to generate output.using System; using System.Text; class RandomText { static Random _random = new Random(); StringBuilder _builder; string[] _words; // Part 1: the constructor. public RandomText(string[] words) { _builder = new StringBuilder(); _words = words; } public void AddContentParagraphs(int numberParagraphs, int minSentences, int maxSentences, int minWords, int maxWords) { // Part 2: call Next() on random number generator for each paragraph. for (int i = 0; i < numberParagraphs; i++) { AddParagraph(_random.Next(minSentences, maxSentences + 1), minWords, maxWords); _builder.Append("\n\n"); } } void AddParagraph(int numberSentences, int minWords, int maxWords) { // Part 3: call AddSentence repeatedly in AddParagraph. for (int i = 0; i < numberSentences; i++) { int count = _random.Next(minWords, maxWords + 1); AddSentence(count); } } void AddSentence(int numberWords) { // Part 4: generate a single sentence. StringBuilder b = new StringBuilder(); // Add n words together. for (int i = 0; i < numberWords; i++) // Number of words { b.Append(_words[_random.Next(_words.Length)]); b.Append(' '); } string sentence = b.ToString().Trim() + ". "; // Uppercase sentence. sentence = char.ToUpper(sentence[0]) + sentence.Substring(1); // Add this sentence to the class. _builder.Append(sentence); } public string Content { get { return _builder.ToString(); } } } class Program { static void Main() { // Part 5: create a RandomText instance and generate text with it. string[] words = { "cat", "house", "man", "the", "for", "and", "a", "with", "bird", "fox" }; RandomText text = new RandomText(words); text.AddContentParagraphs(2, 2, 4, 5, 12); string content = text.Content; Console.WriteLine(content); } }For bird house a house fox cat. House the the man a a bird cat a man for cat. Bird fox for for the a with a cat man. A with the fox cat with bird house.
The class
uses object-oriented design methodology and outputs variable-length sentences and paragraphs. We can specify any number of possible words.