我有一个问题。我需要像这样拆分我的每个字符串: 例如: “经济驱动无限制”
我需要像这样的带有子字符串的数组: “经济驱动无” “无限制驾驶”
现在我有这个:
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++;
}
}
最佳答案
您可以使用此 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();
因为其他人评论说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));
}
关于c# - 字符串每 3 个单词拆分一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32650409/