TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# First Words From String

This C# example program gets the first several words in a string.

First words can be used to summarize text.

They can generate a summary from a string that is much shorter than the entire string. This is useful for RSS and captions. We examine a C# method that counts words and returns the first words.

Input string

This is an example summary that we are using as an example.

First 7 words: output

This is an example summary that we

Example. First we avoid all string copying except one Substring at the return of the method. We simply count spaces as we go over the string. When the number of spaces equals the number of words, we return the Substring.

C# 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 1

This is an example summary that we are using as an example.
This is an example summary that we

Output 2

How many words are in this sentence? We only want the first few.
How many words are in this sentence?

In this example, the first parameter to the method is the string you want to take the first words from. The second parameter is the number of words you want to extract from the start of the string.

It prints out the first seven words of each of the strings in the string array. The second line and the fourth line show only the first seven words. They include punctuation, as the method here only examines spaces.

String Array

Tip: Newlines are not handled by this method. You will need to use char.IsWhiteSpace instead of checking that each character is a space.

char.IsWhiteSpace

Performance: Speed here is good because only one string copy is made. All we are doing here is counting spaces and returning a substring.

Summary. We extracted the first several words from a sentence or string in the C# programming language. Use this C# method and adapt it to your precise needs to extract the first N words from a string.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf