C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Parameter 1: The first parameter is the string you want to take the first words from.
Parameter 2: The second parameter is the number of words you want to extract from the start of the string.
Main: It prints out the first 7 words of each of the strings. The second line and the fourth line show only the first 7 words.
ConsoleArrayWarning: Newlines are not handled by this method. Try using char.IsWhiteSpace instead of checking that each character is a space.
Environment.NewLineCharC# program that gets first words
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void Main()
{
string[] exampleStrings = new string[]
{
"This is an example summary that we are using as an example.",
"How many words are in this sentence? We only want the first few."
};
foreach (string example in exampleStrings)
{
string firstWords = FirstWords(example, 7);
Console.WriteLine(example);
Console.WriteLine(firstWords);
}
}
/// <summary>
/// Get the first several words from the summary.
/// </summary>
public static string FirstWords(string input, int numberWords)
{
try
{
// Number of words we still want to display.
int words = numberWords;
// Loop through entire summary.
for (int i = 0; i < input.Length; i++)
{
// Increment words on a space.
if (input[i] == ' ')
{
words--;
}
// If we have no more words to display, return the substring.
if (words == 0)
{
return input.Substring(0, i);
}
}
}
catch (Exception)
{
// Log the error.
}
return string.Empty;
}
}
Output
This is an example summary that we are using as an example.
This is an example summary that we
How many words are in this sentence? We only want the first few.
How many words are in this sentence?