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

如何实现每4个字符为一组提取并更新char数组的循环?

问题分析与代码修正

原代码核心错误

  1. 索引赋值错误:test[i] = sequence[i] 中误用外层循环的i作为test数组的索引,导致每次都覆盖test的同一个位置,无法正确填充4个字符。
  2. 内层while循环逻辑冗余:外层for循环已在遍历sequence的每个字符,内层while会在第一次循环时连续重复赋值同一个字符,后续重置计数器后又重复错误逻辑。

修正后的代码(逐字符填充版)

#include <stdio.h>

int main() {
    char sequence[32] = "qRiM1uOtGgXl5yuNPJwKo4+bAdQuPUbr";
    char test[4];
    int count_steps = 0;

    for (int i = 0; i < 32; i++) {
        // 用count_steps作为test的索引,依次填充字符
        test[count_steps] = sequence[i];
        count_steps++;

        // 攒够4个字符时处理
        if (count_steps == 4) {
            // 打印当前组(替换为你的decoder调用即可)
            for(int j = 0; j < 4; j++) {
                printf("%c", test[j]);
            }
            printf("\n");

            // 重置计数器,准备下一组
            count_steps = 0;
        }
    }

    return 0;
}

另一种更简洁的实现(直接截取组)

如果sequence长度刚好是4的倍数,也可以直接按步长4遍历起始位置,用strncpy截取每组:

#include <stdio.h>
#include <string.h>

int main() {
    char sequence[32] = "qRiM1uOtGgXl5yuNPJwKo4+bAdQuPUbr";
    char test[4];

    // 每次步长4,处理每组起始位置
    for (int i = 0; i < 32; i += 4) {
        // 从sequence截取4个字符到test
        strncpy(test, &sequence[i], 4);
        // 打印或处理当前组
        for(int j = 0; j < 4; j++) {
            printf("%c", test[j]);
        }
        printf("\n");
    }

    return 0;
}

效果说明

两种代码运行后都会输出:

qRiM
1uOt
GgXl
5yuN
PJwK
o4+b
AdQu
PUbr

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:00:42