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

如何在C#中按指定分隔符拆分字节数组?

按指定分隔字节拆分字节数组

场景说明

给定源字节数组:

byte[] array = {1, 0x2C, 2, 0x2C, 3, 4, 5};

分隔符为0x2C(ASCII逗号的十六进制表示),目标是拆分出所有分隔符分隔的子字节数组,并提取每个子数组的第一个元素,最终得到结果{1, 2, 3}。

实现代码

import java.util.ArrayList;
import java.util.List;

public class ByteSplitExample {
    public static void main(String[] args) {
        byte[] source = {1, 0x2C, 2, 0x2C, 3, 4, 5};
        byte delimiter = 0x2C;

        // 拆分字节数组为子数组列表
        List<byte[]> splitParts = splitByDelimiter(source, delimiter);

        // 提取每个子数组的第一个元素(匹配示例需求)
        byte[] result = new byte[splitParts.size()];
        for (int i = 0; i < splitParts.size(); i++) {
            if (splitParts.get(i).length > 0) {
                result[i] = splitParts.get(i)[0];
            }
        }

        // 输出结果
        System.out.print("result = {");
        for (int i = 0; i < result.length; i++) {
            System.out.print(result[i]);
            if (i < result.length - 1) System.out.print(", ");
        }
        System.out.println("}");
    }

    /**
     * 按指定分隔字节拆分源数组
     * @param source 待拆分的字节数组
     * @param delimiter 分隔字节
     * @return 拆分后的子数组列表
     */
    private static List<byte[]> splitByDelimiter(byte[] source, byte delimiter) {
        List<byte[]> parts = new ArrayList<>();
        int start = 0;

        for (int i = 0; i < source.length; i++) {
            if (source[i] == delimiter) {
                // 截取当前分隔段
                byte[] part = new byte[i - start];
                System.arraycopy(source, start, part, 0, part.length);
                parts.add(part);
                start = i + 1;
            }
        }

        // 处理最后一段无分隔符的内容
        if (start < source.length) {
            byte[] part = new byte[source.length - start];
            System.arraycopy(source, start, part, 0, part.length);
            parts.add(part);
        }

        return parts;
    }
}

代码说明

  1. 核心拆分逻辑:splitByDelimiter方法遍历源数组,每遇到分隔符就截取从上次起始位置到当前索引的子数组,加入结果列表;遍历结束后处理最后一段未被分隔符截断的内容。
  2. 示例需求适配:拆分后得到的子数组分别是{1}、{2}、{3,4,5},提取每个子数组的第一个元素就得到了目标结果。如果只需要拆分后的子数组,直接使用splitParts列表即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:05:33