Tim*_*ter 27
你需要拆分字符串.您可以使用不带参数的重载(假定为空格).
IEnumerable<string> words = str.Split().Take(250);
Run Code Online (Sandbox Code Playgroud)
请注意,您需要添加using System.Linq
的Enumerable.Take
.
您可以使用ToList()
或ToArray()
从查询中创建新集合或保存内存并直接枚举它:
foreach(string word in words)
Console.WriteLine(word);
Run Code Online (Sandbox Code Playgroud)
更新
由于它似乎很受欢迎,我正在添加以下扩展,它比Enumerable.Take
方法更有效,并且还返回集合而不是(延迟执行)查询.
它采用了String.Split
其中的空白字符被认为是分隔符,如果分离器的参数为空或不包含任何字符.但该方法还允许传递不同的分隔符:
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;
}
Run Code Online (Sandbox Code Playgroud)
它可以很容易地使用:
string str = "A B C D E F";
string[] words = str.GetWords(5, null, StringSplitOptions.RemoveEmptyEntries); // A,B,C,D,E
Run Code Online (Sandbox Code Playgroud)
yourString.Split(' ').Take(250);
Run Code Online (Sandbox Code Playgroud)
我猜.你应该提供更多信息.