首页 > 解决方案 > 如何将文本 2 拆分为 2?

问题描述

变量是:你好我想要的结果:

split[0] = he;
split[1] = ll;
split[2] = o + ( space );

我试过这段代码:

string[] split = new string[text.Length / 2 + (text.Length % 2 == 0 ? 0 : 1)];
for (int i = 0; i < split.Length; i++)
{
  split[i] = text.Substring(i, i + 2 > text.Length ? 1 : 2);
}

输出是“He el lo”(它将第二个字符加倍)。

标签: c#arraysstringsplit

解决方案


尝试这个:

string input = "Hello"
string[] split = new string[input.Length / 2 + (input.Length % 2 == 0 ? 0 : 1)];
for (int i = 0; i < input.Length; i+=2)
{
    split[i/2] = input.Substring(i, i + 2 > input.Length ? 1 : 2);
}

这以 2 为增量逐步遍历输入字符串,一次占用 2 个字符。


推荐阅读