
A first sentence has importance. How can you get the first sentence in a paragraph? Parsing the English language is exceedingly hard. Instead of aiming for a perfect implementation, we present here a simple method.
The FirstSentence method presented here loops through the paragraph string beginning at the first character. When the period '.' is encountered, it checks that the period is followed by a whitespace. This signals the end of a sentence. Additionally, the '?' and the '!' characters are considered to be sentence ending characters.
This C# example program gets the first sentence from a paragraph. It uses a for-loop and switch statement.
Program that gets first sentence [C#]
using System;
class Program
{
static void Main()
{
string paragraph = "Thank you for visiting this article. There are " +
"more articles on this website.";
Console.WriteLine(FirstSentence(paragraph));
paragraph = "How can you make more money? The easiest thing to do " +
"would be to spend less.";
Console.WriteLine(FirstSentence(paragraph));
}
public static string FirstSentence(string paragraph)
{
for (int i = 0; i < paragraph.Length; i++)
{
switch (paragraph[i])
{
case '.':
if (i < (paragraph.Length - 1) &&
char.IsWhiteSpace(paragraph[i + 1]))
{
goto case '!';
}
break;
case '?':
case '!':
return paragraph.Substring(0, i + 1);
}
}
return paragraph;
}
}
Output
Thank you for visiting this article.
How can you make more money?
Explanation for period logic. The reason we require ". " and not just "." for the ending character of a sentence is that many abbreviations are used in the English language. For example, a website containing a URL like "www.dotnetperls.com" does not have sentence ending characters in it. It is simply a word that has periods in it.
Note: Unfortunately, this method has weaknesses. It will consider the title "Mr. " to end a sentence. Creating a method that handles all cases in the English language would be very challenging.

Sometimes, a simple method that handles most cases in your data is appropriate. This method will work for many writing samples that do not include certain words. One of the most interesting challenges in computer programming is handling natural languages; this task is best left for other articles.
Algorithms