好吧,string.Split() 仅由 空格 分割
https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=net-6.0
Split 用于将分隔字符串拆分为子字符串。您可以使用字符数组或字符串数组来指定零个或多个分隔字符或字符串。如果没有指定分隔符,则字符串将在空白个字符处分割。
粗体是我的。
到目前为止一切顺利,string.Split() 在 空格 ' ',制表 '\t',换行 '\n', 回车'\r'等:
Console.Write(string.Join(", ", "a\nb\rc\td e".Split()));
生产
a, b, c, d, e
如果你想分割你的牛分隔符,你应该提供它们:
Console.Write(string.Join(", ", "a\nb\rc\td e".Split(new char[] {' ', '\t'})));
注意\r 和\n 在' ' 和't' 上拆分时被保留
a
b
c, d, e
所以,看来你的方法应该是这样的:
using System.Linq;
...
//DONE: static - we don't want this here
public static string SplitXWord(string text, int wordCount) {
//DONE: don't forget about degenerated cases
if (string.IsNullOrWhiteSpace(text) || wordCount <= 0)
return "";
//TODO: specify delimiters on which you want to split
return string.Join(" ", text
.Split(
new char[] { ' ', '\t' },
wordCount + 1,
StringSplitOptions.RemoveEmptyEntries)
.Take(wordCount));
}