Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c# - Get first 250 words of a string?

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...