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

C语言中如何将多个字母拼接为完整的单词字符串?

C语言按字符数拼接单词实现方案

实现逻辑

  • 定义长度为6的临时字符数组存储待拼接单词(预留1位存储字符串结束符'\0')
  • 新增变量记录当前临时单词已存入的字符数
  • 每收集到1个有效字母就存入临时数组,计数累加,计数到5时补'\0'得到完整单词
  • 处理完当前单词后重置临时数组和计数,准备收集下一个单词

修正后可运行代码

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

int main() {
    // 你的原有变量,count请提前自行赋值有效数值,最大不超过20
    int count = 5;
    char validStrings[20][50] = {""};
    // 新增拼接用变量
    char tempWord[6] = {0};
    int curWordLen = 0;
    int secondCount = 0;

    for (int j = 0 ; j < 10; ++j){
        for (int k = 0 ; k < count ; ++k){
            char letter = validStrings[k][j];
            // 可选:过滤非字母字符,不需要可以删掉该判断
            if ((letter >= 'a' && letter <= 'z') || (letter >= 'A' && letter <= 'Z')) {
                tempWord[curWordLen] = letter;
                curWordLen++;
                secondCount++;
            }
            // 收集满5个字符处理逻辑
            if(secondCount == 5){
                tempWord[curWordLen] = '\0';
                // 此处可自定义单词处理逻辑,比如存入其他数组、打印等
                printf("拼接完成的单词:%s\n", tempWord);
                // 重置状态
                memset(tempWord, 0, sizeof(tempWord));
                curWordLen = 0;
                secondCount = 0;
                putchar('\n');
            }
        }
    }
    return 0;
}

注意事项

  • 数组访问时不要越界,count变量的取值不能超过validStrings第一维的最大长度20,j的遍历上限不能超过第二维长度50
  • 如果需要持久化存储所有拼接完成的单词,可以定义二维数组char savedWords[20][6],每次得到完整单词后调用strcpy(savedWords[wordIndex], tempWord)存储,再将wordIndex累加即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:45:01