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

如何在不转换类型的unsigned char数组中删除指定范围元素

处理unsigned char数组的指定范围删除需求

原始数组与目标效果

原始数组:

unsigned char arr[]= "ksd sjdhkd 08923 jh32jk3 323hkgk \34 \34 \er \fd\3 \3df \34f ";

需要删除从"ksd"到第一个"\34"(八进制转义字符,对应ASCII值28)的所有元素,最终得到:

unsigned char arr[]= " \34 \er \fd\3 \3df \34f ";

实现思路(满足要求:不转字符串、保持unsigned char类型)

  • 遍历数组定位起始点:找到连续三个元素为'k'、's'、'd'的索引位置
  • 从起始点继续遍历,找到第一个值为0x1C(即\34对应的十进制值28)的结束索引
  • 将结束索引之后的所有元素向前覆盖到起始索引位置,最后补全字符串终止符'\0'

代码实现

#include <stdio.h>

int main() {
    unsigned char arr[]= "ksd sjdhkd 08923 jh32jk3 323hkgk \34 \34 \er \fd\3 \3df \34f ";
    
    // 定位起始位置:找到连续的'k' 's' 'd'
    unsigned int start_idx = 0;
    while (arr[start_idx] != '\0' && !(arr[start_idx] == 'k' && arr[start_idx+1] == 's' && arr[start_idx+2] == 'd')) {
        start_idx++;
    }
    // 未找到起始序列则终止处理
    if (arr[start_idx] == '\0') {
        printf("未找到起始序列'ksd'\n");
        return 1;
    }
    
    // 定位结束位置:从start_idx开始找第一个'\34'(即0x1C)
    unsigned int end_idx = start_idx;
    while (arr[end_idx] != '\0' && arr[end_idx] != 0x1C) {
        end_idx++;
    }
    // 未找到结束字符则终止处理
    if (arr[end_idx] == '\0') {
        printf("未找到结束字符\\34\n");
        return 1;
    }
    
    // 移动元素:将end_idx+1后的内容覆盖到start_idx位置
    unsigned int move_idx = 0;
    while (arr[end_idx + 1 + move_idx] != '\0') {
        arr[start_idx + move_idx] = arr[end_idx + 1 + move_idx];
        move_idx++;
    }
    // 补终止符确保数组合法
    arr[start_idx + move_idx] = '\0';
    
    // 输出验证结果
    printf("处理后数组内容:%s\n", arr);
    return 0;
}

说明

  • 代码直接操作unsigned char数组,未进行任何字符串类型转换
  • 遍历过程通过元素值匹配定位目标范围,完全符合需求限制
  • 加入边界检查,避免因未找到起始/结束序列导致的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:35:12