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

C语言如何使用stdio.h和string.h函数实现连续字符序列缩写

可使用的stdio.h与string.h函数清单

string.h 适用函数

  • strlen():获取输入字符串的总长度,确定遍历边界
  • strcat()/strncat():将生成的片段(如"a-f"、单个字符)拼接进结果缓冲区,推荐使用带长度限制的strncat()避免缓冲区溢出
  • strcpy()/strncpy():用于初始化结果缓冲区或复制短片段,strncpy()安全性更高

stdio.h 适用函数

  • sprintf()/snprintf():直接格式化输出连续段到结果缓冲区,比如检测到3个及以上连续递增字符时,可直接用snprintf(buf + offset, buf_remaining, "%c-%c", start_char, current_char)生成短横线格式片段,无需手动拼接字符,snprintf()可指定剩余缓冲区长度避免溢出
  • fputs()/puts():如果需求是直接输出结果而非返回字符串,可直接用这两个函数输出最终内容

实现参考示例

核心逻辑:遍历字符串记录连续递增序列的起始位置,连续长度≥3时输出「首字符-尾字符」格式,否则直接输出原字符。

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

void compress_continuous(const char *input, char *output, size_t output_size) {
    if (input == NULL || output == NULL || output_size == 0) return;
    size_t input_len = strlen(input); // 调用string.h的strlen获取输入长度
    if (input_len == 0) {
        output[0] = '\0';
        return;
    }
    size_t out_pos = 0;
    char seq_start = input[0];
    int continuous_count = 1;

    for (size_t i = 1; i <= input_len; i++) {
        // 判断是否仍为连续递增序列
        if (i < input_len && input[i] == input[i-1] + 1) {
            continuous_count++;
        } else {
            if (continuous_count >= 3) {
                // 调用stdio.h的snprintf格式化连续段
                out_pos += snprintf(output + out_pos, output_size - out_pos, "%c-%c", seq_start, input[i-1]);
            } else {
                // 连续长度不足3直接写入原字符
                for (int j = 0; j < continuous_count && out_pos < output_size - 1; j++) {
                    output[out_pos++] = seq_start + j;
                }
            }
            seq_start = input[i];
            continuous_count = 1;
        }
    }
    output[out_pos] = '\0';
}

// 测试用例
int main() {
    char res_letter[10], res_num[10];
    compress_continuous("abcdef", res_letter, sizeof(res_letter));
    compress_continuous("56789", res_num, sizeof(res_num));
    printf("%s\n%s\n", res_letter, res_num); // 输出a-f和5-9
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:45:10