C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Also: In the switch, the "?" and the "!" characters are considered sentence ending characters.
C# program that gets first sentence
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?
Note: This method has weaknesses. It will consider the title "Mr" to end a sentence. This problem occurs in other places too.
However: Creating a method that handles all cases in the English language is challenging.