We avoid all string copying except one Substring. We count spaces as we go over the string. When the number of spaces equals the number of words, we return the Substring.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void Main()
{
Console.WriteLine(FirstWords(
"The bird is blue", 2));
Console.WriteLine(FirstWords(
"This sentence has many words.", 4));
}
/// <summary>
/// Get the first several words from the summary.
/// </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] == '
')
{
words--;
}
// If we have no more words to display, return the substring.
if (words == 0)
{
return input.Substring(0, i);
}
}
return string.Empty;
}
}
The bird
This sentence has many