You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#将字符串拆分为由两个字符子串组成的数组

问题根因

原有代码存在两个问题:

  • 循环步长为1,每次取子串后仅移动1位,导致子串重叠
  • 数组初始化长度为原字符串长度,会产生大量无用的空值元素

修正代码(符合你给出的abcdef拆分需求,奇数长度字符串时自动丢弃最后单个不足2位的字符)

static string[] mymethod(string str)
{
    int arrayLength = str.Length / 2;
    string[] r = new string[arrayLength];
    for (int i = 0, index = 0; i < str.Length - 1; i += 2, index++)
    {
        r[index] = str.Substring(i, 2);
    }
    return r;
}

如果需要兼容奇数长度的字符串,保留最后剩下的单个字符,可以使用下面的版本:

static string[] mymethod(string str)
{
    int arrayLength = (str.Length + 1) / 2;
    string[] r = new string[arrayLength];
    for (int i = 0, index = 0; i < str.Length; i += 2, index++)
    {
        int takeLength = Math.Min(2, str.Length - i);
        r[index] = str.Substring(i, takeLength);
    }
    return r;
}

内容的提问来源于stack exchange,提问作者user16612111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 14:39:03