Home
C#
String First Words
Updated Jul 7, 2021
Dot Net Perls
First words. First words can be used to summarize text. They can generate a summary from a string that is much shorter than the entire string.
Notes, usefulness. This logic is useful for summaries and captions. We examine a C# method that counts words and returns the first words.
String Substring
Input and output. Suppose we have a phrase like "the bird is blue." We can take only the first 2 words from this phrase, leaving us with "the bird" only.
Input: The bird is blue Words(2): The bird
An example. 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.
Argument 1 The first parameter is the string you want to take the first words from.
Argument 2 The second parameter is the number of words you want to extract from the start of the string.
Console.WriteLine
Array
Warning Newlines are not handled by this method. Try using char.IsWhiteSpace instead of checking that each character is a space.
Environment.NewLine
char
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
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 7, 2021 (edit).
Home
Changes
© 2007-2025 Sam Allen