Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first 250 words of a string?

Tags:

string

c#

How do I get the first 250 words of a string?

like image 836
Edwin Torres Avatar asked Nov 13 '12 20:11

Edwin Torres


People also ask

How do you get the first word of a string?

To get the first word of a string:Call the split() method passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Access the array at index 0 to get the first word of the string.

How do you extract the first 10 words of a string in Python?

We can use the re. findall() function in python to get the first n words in a given string. This function returns a list of all the matches in the given string.

How do you get the first 5 characters of a string?

string str = (yourStringVariable + " "). Substring(0,5). Trim();


1 Answers

You need to split the string. You can use the overload without parameter(whitespaces are assumed).

IEnumerable<string> words = str.Split().Take(250);

Note that you need to add using System.Linq for Enumerable.Take.

You can use ToList() or ToArray() ro create a new collection from the query or save memory and enumerate it directly:

foreach(string word in words)
    Console.WriteLine(word);

Update

Since it seems to be quite popular I'm adding following extension which is more efficient than the Enumerable.Take approach and also returns a collection instead of the (deferred executed) query.

It uses String.Split where white-space characters are assumed to be the delimiters if the separator parameter is null or contains no characters. But the method also allows to pass different delimiters:

public static string[] GetWords(
       this string input,
       int count = -1,
       string[] wordDelimiter = null,
       StringSplitOptions options = StringSplitOptions.None)
{
    if (string.IsNullOrEmpty(input)) return new string[] { };

    if(count < 0)
        return input.Split(wordDelimiter, options);

    string[] words = input.Split(wordDelimiter, count + 1, options);
    if (words.Length <= count)
        return words;   // not so many words found

    // remove last "word" since that contains the rest of the string
    Array.Resize(ref words, words.Length - 1);

    return words;
}

It can be used easily:

string str = "A B C   D E F";
string[] words = str.GetWords(5, null, StringSplitOptions.RemoveEmptyEntries); // A,B,C,D,E
like image 122
Tim Schmelter Avatar answered Oct 19 '22 22:10

Tim Schmelter