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

如何改造C#固定长度字符串拆分方法为按指定长度数组拆分?

问题根因
  • 索引偏移变量位置错误:你将当前读取位置变量i定义在了foreach循环内部,每次遍历数组里的拆分长度时,i都会被重置为0,导致每次截取都从字符串开头位置计算,无法实现逐段向后拆分的效果。
  • 缺少单段长度合法性校验:没有校验数组内的每个拆分长度是否≥1,若传入的数组包含≤0的数值,会直接触发Substring方法的参数异常。
  • 缺少边界场景处理:如果数组内的所有拆分长度总和小于原字符串总长度,没有定义剩余字符的处理规则,可根据业务需求选择丢弃剩余字符,或追加到结果末尾。
修正后的实现代码
public static IEnumerable<string> SplitBy(this string str, int[] chunkLengths)
{
    if (string.IsNullOrEmpty(str)) 
        throw new ArgumentException("待拆分字符串不能为空或null", nameof(str));

    if (chunkLengths == null || chunkLengths.Length < 1) 
        throw new ArgumentException("拆分长度数组不能为空且至少要有一个元素", nameof(chunkLengths));
    
    // 偏移量定义在循环外部,记录当前读取位置
    int currentIndex = 0;
    foreach (int chunkLength in chunkLengths)
    {
        if (chunkLength < 1)
            throw new ArgumentException($"拆分长度不能小于1,异常值:{chunkLength}", nameof(chunkLengths));
        // 已经到字符串末尾就直接终止
        if (currentIndex >= str.Length)
            break;
        
        // 计算实际要截取的长度,避免超出字符串范围
        int actualLength = Math.Min(chunkLength, str.Length - currentIndex);
        yield return str.Substring(currentIndex, actualLength);
        currentIndex += actualLength;
    }

    // 如果需要返回数组拆分完后剩余的字符,放开下面的注释即可
    // if (currentIndex < str.Length)
    // {
    //     yield return str.Substring(currentIndex);
    // }
}
效果验证

调用示例:"bobjoecat".SplitBy(new int[]{6,3}),返回结果为["bobjoe", "cat"],符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:12:02