c - 获取字符串直到第一个数字
问题描述
我需要从数组中获取第一个数字之前的所有字符。我这样做了,它似乎工作正常:
#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;
}
我想知道我是否可以用更少的指令做同样的事情,所以以更好的方式。
解决方案
函数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;
}
推荐阅读
- angular - 对同一项目中的管道进行一次调用
- node.js - 你能通过 Node.js 运行 excel 宏吗
- javascript - 如何在 jquery/ajax 中中止和取消 XHR 挂起请求?
- android - 导航错误 - 此导航图未引用任何布局文件?
- javascript - 将柏树文件部署到詹金斯时如何解决“找不到模块'fs-extra' - 错误”?
- c# - 如何在代码后面通过公共路径动态地对项目进行分组?
- python - Python3 不能在 else 语句之后重复循环(谷歌搜索并没有找到可靠的结果)
- sql - ON DELETE CASCADE 用于 Sequelize 的多个外键
- c# - 如何从 webmethod 获取响应并传递 sql 参数
- python - Reverse only numbers from file