我有一个问题.我需要像这样拆分我的每一个字符串:例如:"没有限制的经济驱动"
我需要带有子字符串的数组:"经济驱动没有""驱动没有限制"
现在我有这个:
List<string> myStrings = new List<string>();
foreach(var text in INPUT_TEXT) //here is Economic drive without restrictions
{
myStrings.DefaultIfEmpty();
var textSplitted = text.Split(new char[] { ' ' });
int j = 0;
foreach(var textSplit in textSplitted)
{
int i = 0 + j;
string threeWords = "";
while(i != 3 + j)
{
if (i >= textSplitted.Count()) break;
threeWords = threeWords + " " + textSplitted[i];
i++;
}
myStrings.Add(threeWords);
j++;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用此LINQ查询:
string text = "Economic drive without restrictions";
string[] words = text.Split();
List<string> myStrings = words
.Where((word, index) => index + 3 <= words.Length)
.Select((word, index) => String.Join(" ", words.Skip(index).Take(3)))
.ToList();
Run Code Online (Sandbox Code Playgroud)
因为其他人评论说,因为OP正在学习这种语言,所以显示循环版本会更好,这里是一个根本不使用LINQ的版本:
List<string> myStrings = new List<string>();
for (int index = 0; index + 3 <= words.Length; index++)
{
string[] slice = new string[3];
Array.Copy(words, index, slice, 0, 3);
myStrings.Add(String.Join(" ", slice));
}
Run Code Online (Sandbox Code Playgroud)