gpt4 book ai didi

c - 如何从c中的字符串中提取数字?

转载 作者:太空狗 更新时间:2023-10-29 16:33:06 29 4
gpt4 key购买 nike

假设我有一个像 ab234cid*(s349*(20kd 这样的字符串,我想提取所有数字 234, 349, 20,我该怎么办?

最佳答案

您可以使用 strtol 来完成,像这样:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
// Found a number
long val = strtol(p, &p, 10); // Read number
printf("%ld\n", val); // and print it.
} else {
// Otherwise, move on to the next character.
p++;
}
}

链接到 ideone .

关于c - 如何从c中的字符串中提取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13399594/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com