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

如何使用C字符串实现字母与数字的拆分分词?

纯C实现字母与数字拆分并存入二维字符数组

给定C字符串:

char s[20] = "fd50 fd 50 fd 5  0";

需要将其拆分后存入二维字符数组token,最终结果要求:

token[0] = "fd"
token[1] = "50"
token[2] = "fd"
token[3] = "50"
token[4] = "fd"
token[5] = "50"

核心要求是把连续的字母和连续的数字分开存储,同时忽略空格。以下是纯C语言的实现方案:

实现思路

  1. 遍历原字符串,用两个指针标记当前子串的起始位置和当前遍历位置;
  2. 区分字符类型(字母/数字/空格):
    • 遇到空格直接跳过,不记录;
    • 当遍历到的字符类型和起始位置字符类型不同时,截取当前子串存入token,并更新起始位置;
  3. 遍历结束后,处理最后一段未存入的子串;
  4. 给每个子串末尾加上字符串结束符'\0',保证C字符串的有效性。

完整代码示例

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

int main() {
    char s[20] = "fd50 fd 50 fd 5  0";
    // 定义二维数组,假设最多10个token,每个token最多10个字符,可按需调整
    char token[10][10] = {0};
    int token_idx = 0;
    int str_len = strlen(s);
    int start = 0;

    for (int i = 0; i <= str_len; i++) {
        // 触发分割的三种情况:遍历到字符串末尾、遇到空格、字符类型切换
        if (i == str_len || isspace(s[i]) || 
            (isalpha(s[start]) && isdigit(s[i])) || 
            (isdigit(s[start]) && isalpha(s[i]))) {
            
            // 跳过空片段(比如连续空格或起始就是空格的情况)
            if (i > start && !isspace(s[start])) {
                // 复制子串到token数组
                strncpy(token[token_idx], s + start, i - start);
                // 手动添加字符串结束符
                token[token_idx][i - start] = '\0';
                token_idx++;
            }
            // 跳过后续连续空格,更新起始位置
            while (i < str_len && isspace(s[i])) {
                i++;
            }
            start = i;
        }
    }

    // 打印结果验证
    for (int i = 0; i < token_idx; i++) {
        printf("token[%d] = \"%s\"\n", i, token[i]);
    }

    return 0;
}

代码说明

  • 使用isalpha()和isdigit()判断字符类型,需包含<ctype.h>头文件;
  • 二维数组token的大小可根据实际场景调整,避免溢出;
  • 处理连续空格时直接跳过,不会生成空的token项;
  • 遍历到字符串末尾时,会自动处理最后一段有效子串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:52:43