static void Main()
Console.WriteLine(FirstWords("The bird is blue", 2));
Console.WriteLine(FirstWords("This sentence has many words.", 4));
/// Get the first several words from the summary.
public static string FirstWords(string input, int numberWords)
// 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] == ' ')
// If we have no more words to display, return the substring.
if (words == 0)
return input.Substring(0, i);
This sentence has many
Notes, performance. Speed here is good because only one string copy is made. All we are doing here is counting spaces and returning a substring.
A summary. We extracted the first several words from a sentence. Use this C# method and adapt it to your precise needs to extract the first words from a string.