Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
299 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...