我从用户那里得到以下字符串:char*abc ="a234bc567d"; 但是所有数字的长度都不同于这个例子(字母是常量).我怎样才能得到数字的每一部分?(再次,它可以是234或23743或其他东西..)
我尝试使用strchr和strncpy,但我需要为此分配内存(对于strncpy),我希望有更好的解决方案.
谢谢.
你可以这样做:
char *abc = "a234bc567d";
char *ptr = abc; // point to start of abc
// While not at the end of the string
while (*ptr != '\0')
{
// If position is the start of a number
if (isdigit(*ptr))
{
// Get value (assuming base 10), store end position of number in ptr
int value = strtol(ptr, &ptr, 10);
printf("Found value %d\n", value);
}
else
{
ptr++; // Increase pointer
}
}
Run Code Online (Sandbox Code Playgroud)