首页 > 解决方案 > 获取字符串直到第一个数字

问题描述

我需要从数组中获取第一个数字之前的所有字符。我这样做了,它似乎工作正常:

#include <stdio.h>

int main() {
    char temp[128] = {0};
    char str_active[128] = {0};

    sprintf(temp, "%s", "AB01");
    printf("Complete string.: %s\n", temp);

    int len = sizeof(temp) / sizeof(char);
    int index = 0;
    while (index < len) {
        if (isdigit(temp[index])) {
            break;
        } else {
            index++;
        }
    }
    snprintf(str_active, index + 1, "%s\n", temp);
    printf("String before first digit.: %s\n", str_active);

    return 0;
}

我想知道我是否可以用更少的指令做同样的事情,所以以更好的方式。

标签: carraysstring

解决方案


函数strcspn可以为您完成:

strcspn() 函数计算 s 的初始段的长度,该段完全由未拒绝的字节组成。

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

int main() {

    char temp[128] = {0};
    char str_active[128] = {0};

    sprintf(temp, "%s", "AB01");
    printf("Complete string.: %s\n", temp);

    strncpy(str_active, temp, strcspn(temp, "0123456789"));
    printf("String before first digit.: %s\n", str_active);

    return 0;
}

推荐阅读