得到一个字符串的第一个250字? [英] Get first 250 words of a string?
问题描述
我如何得到一个字符串的第一个250字?
How do I get the first 250 words of a string?
推荐答案
您需要分割字符串。您可以使用超载无参数(假定空格)
You need to split the string. You can use the overload without parameter(whitespaces are assumed).
IEnumerable<string> words = str.Split().Take(250);
请注意,您需要添加使用System.Linq的
为 Enumerable.Take
。
Note that you need to add using System.Linq
for Enumerable.Take
.
您可以使用了ToList()
或 ToArray的()
RO从查询中创建一个新的集合或节省存储空间,并直接列举的:
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);
更新
由于它似乎是相当受欢迎的,我加入下面的扩展,它比 Enumerable.Take
办法更有效,也返回一个集合,而不是(延迟执行)的查询的
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.
它使用 String.Split
其中空白字符假定为分隔符如果隔板参数为空或不包含的字符。但该方法也可以通过不同的分隔符:
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
这篇关于得到一个字符串的第一个250字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!