c# - 字符串每 3 个单词拆分一次

标签 c# string split

我有一个问题。我需要像这样拆分我的每个字符串: 例如: “经济驱动无限制”

我需要像这样的带有子字符串的数组: “经济驱动无” “无限制驾驶”

现在我有这个:

            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/

相关文章:

php - 将 float 格式化为两位小数

string - Golang 中的 *string 和 string 有什么区别?

c - 通过插入空字符在C中分割字符串

c# - Entity Framework Core 从现有数据库创建模型

c# - AppDomain.CurrentDomain.ProcessExit 不执行 Console.WriteLine

c# - 从其他列表中查找 id

c# - 如何在函数应用程序中测试函数级别授权以进行本地开发?

python - 如何将字符串指针传递给共享库?

vim - 如何在 vimdiff 中切换垂直和水平分割?

java - 用多个空格分割字符串