C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: This example will generate two paragraphs that contain between 2 and 4 sentences. Each sentence will contain between 5 and 12 words.
Content: The class outputs text that has a certain number of paragraphs, separated by newlines.
And: Within those paragraphs, there are random numbers of sentences. Within those sentences, there is a random number of words.
C# program that creates random text
using System;
class Program
{
static void Main()
{
string[] words = { "anemone", "wagstaff", "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);
}
}
Output
And the a anemone for bird.
Anemone with man and man the and with fox fox the.
With the for man the.
Anemone with the a wagstaff and man for fox.
A anemone a bird anemone anemone anemone bird wagstaff a bird.
Constructor: We specify the options first in the constructor, which accepts the list of words to use.
AddContentParagraphs: This uses the Random instance's Next method. It adds the paragraph. After the paragraph, it inserts 2 line breaks.
RandomStringBuilderPrivate methods: The 2 private methods in the class simply add a variable number of sentences and then the sentence itself.
Public, privateClass for generating text: C#
public class RandomText
{
static Random _random = new Random();
StringBuilder _builder;
string[] _words;
public RandomText(string[] words)
{
_builder = new StringBuilder();
_words = words;
}
public void AddContentParagraphs(int numberParagraphs, int minSentences,
int maxSentences, int minWords, int maxWords)
{
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)
{
for (int i = 0; i < numberSentences; i++)
{
int count = _random.Next(minWords, maxWords + 1);
AddSentence(count);
}
}
void AddSentence(int numberWords)
{
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)]).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();
}
}
}
Finally: The AddSentence method trims the output and adds a period at the end of your sentence.
And: It uses the char.ToUpper method to capitalize the first letter of the sentence. It appends the sentence to the internal buffer.
char.ToLower