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

如何按“取3跳1”规则分割无结尾空格的C#字符串?

字符串按固定规则分割的解决方案

需求说明

原始字符串:

string str = "[A]     [C]     [E] [F]";

期望分割后的集合:

List<string> myList = {"[A]", "   ", "[C]", "   ", "[E]", "[F]"};

分割规则:每取3个字符,然后跳过1个字符,但原字符串末尾没有空格,直接给字符串长度加1会因最后一组不足4字符报错。

实现方案

通过循环遍历字符串,按规则截取子串,同时处理末尾剩余字符:

List<string> myList = new List<string>();
int index = 0;
int length = str.Length;

while (index < length)
{
    // 取当前位置开始的最多3个字符,避免越界
    int takeLength = Math.Min(3, length - index);
    myList.Add(str.Substring(index, takeLength));
    
    // 跳过1个字符,确保索引不超出字符串长度
    index += takeLength + 1;
}

代码说明

  • 用Math.Min(3, length - index)保证最后一次截取不会超出字符串范围,适配末尾不足3个字符的情况
  • 每次截取后索引增加“截取长度+1”,严格执行“取3跳1”的规则,无需给原字符串补空格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:05:18