获得一个字符串的前250个单词?

如何获得字符串的前250个单词?

你需要拆分字符串。 您可以使用不带参数的重载 (假定为空格)。

 IEnumerable words = str.Split().Take(250); 

请注意,您需要using System.LinqEnumerable.Take添加。

您可以使用ToList()ToArray()从查询创建新集合或保存内存并直接枚举它:

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

更新

由于它似乎很受欢迎,我正在添加以下扩展,它比Enumerable.Take方法更有效,并且还返回集合而不是(延迟执行) 查询

它使用String.Split ,如果separator参数为null或不包含任何字符,则假定空格字符为分隔符。 但该方法还允许传递不同的分隔符:

 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; } 

它可以很容易地使用:

 string str = "ABCDEF"; string[] words = str.GetWords(5, null, StringSplitOptions.RemoveEmptyEntries); // A,B,C,D,E 
 yourString.Split(' ').Take(250); 

我猜。 你应该提供更多信息。

String.Join(“”,yourstring.Split()。Take(250)。ToArray())

除了蒂姆回答,这是你可以尝试的

 IEnumerable words = str.Split().Take(250); StringBuilder firstwords = new StringBuilder(); foreach(string s in words) { firstwords.Append(s + " "); } firstwords.Append("..."); Console.WriteLine(firstwords.ToString()); 

试试这个:

 public string TakeWords(string str,int wordCount) { char lastChar='\0'; int spaceFound=0; var strLen= str.Length; int i=0; for(; i 

没有调用Take()就可以。

 string[] separatedWords = stringToProcess.Split(new char[] {' '}, 250, StringSplitOptions.RemoveEmptyEntries); 

这也允许基于不仅仅是空格“”进行拆分,因此可以在输入中错误地缺少空格时修复出现。

 string[] separatedWords = stringToProcess.Split(new char[] {' ', '.', ',' ':', ';'}, 250, StringSplitOptions.RemoveEmptyEntries); 

如果要返回空字符串,请使用StringSplitOptions.None