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

如何在C语言中过滤字符串中的空白字符及转义空白序列?

C语言字符串过滤:移除空白字符与转义空白序列

以下是实现需求的filter_whitespace函数,同时包含测试示例:

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

void filter_whitespace(const char *src, char *dest, size_t dest_size) {
    if (src == NULL || dest == NULL || dest_size == 0) {
        return;
    }

    size_t src_idx = 0;
    size_t dest_idx = 0;
    char current_char;

    while ((current_char = src[src_idx]) != '\0') {
        // 捕获并跳过转义空白序列:\t、\n、\r、\f、\v
        if (current_char == '\\') {
            char next_char = src[src_idx + 1];
            if (next_char == 't' || next_char == 'n' || next_char == 'r' || 
                next_char == 'f' || next_char == 'v') {
                src_idx += 2;
                continue;
            }
        }

        // 跳过实际的空白字符
        if (current_char == ' ' || current_char == '\t' || current_char == '\n' || 
            current_char == '\r' || current_char == '\f' || current_char == '\v') {
            src_idx++;
            continue;
        }

        // 写入非空白字符,确保缓冲区不溢出
        if (dest_idx < dest_size - 1) {
            dest[dest_idx] = current_char;
            dest_idx++;
        }
        src_idx++;
    }

    // 终止目标字符串
    dest[dest_idx] = '\0';
}

// 测试用例
int main() {
    char input1[] = "ab \t\nc";
    char output1[100];
    filter_whitespace(input1, output1, sizeof(output1));
    printf("输入1: '%s' → 输出1: '%s'\n", input1, output1);

    char input2[] = "\"abcd \n\t ef   \"";
    char output2[100];
    filter_whitespace(input2, output2, sizeof(output2));
    printf("输入2: '%s' → 输出2: '%s'\n", input2, output2);

    // 测试转义序列的情况
    char input3[] = "hello\\tworld\\nfoo";
    char output3[100];
    filter_whitespace(input3, output3, sizeof(output3));
    printf("输入3: '%s' → 输出3: '%s'\n", input3, output3);

    return 0;
}

关键逻辑说明

  1. 参数合法性检查:先排除空指针、空缓冲区等非法输入,避免程序崩溃。
  2. 转义序列处理:当遇到反斜杠\时,立即检查后续字符是否是t/n/r/f/v这些标准空白转义符,若是则直接跳过这两个字符,不写入结果。
  3. 实际空白过滤:直接匹配空格、制表符、换行、回车等实际空白字符,遇到则跳过。
  4. 缓冲区安全:写入结果时严格控制索引,确保不超过目标缓冲区的大小(预留一个字节给字符串终止符\0),防止缓冲区溢出。
  5. 字符串终止:最后必须手动添加\0,保证输出是合法的C字符串。

运行测试用例后,输出结果如下:

输入1: 'ab 	
c' → 输出1: 'abc'
输入2: '"abcd 	
 ef   "' → 输出2: '"abcdef"'
输入3: 'hello\tworld\nfoo' → 输出3: 'helloworldfoo'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:35:36