回复 6楼 T_MACC
先遍历数组,在第一个条件if (str[i] >= '0' && str[i] <= '9')找到数字字符,然后第二次遍历数组,在条件if (str[i] < '0' && str[i] > '9')
找到数字字符结束的地方,然后提取这段每个数字字符处理。
#include <stdio.h> unsigned foo( const char* s ) { unsigned ret = 0; while( *s ) { int i = 0; sscanf( s, "%*[^0-9]%n", &i ); s += i; unsigned val = 0; i = 0; sscanf( s, "%u%n", &val, &i ); s += i; ret += val; } return ret; } int main( void ) { printf( "%u\n", foo("abc123def45gh678") ); return 0; }
#include <stdio.h> unsigned foo( const char* s ) { unsigned ret = 0; unsigned m = 0; for( const char* p=s; *p; ++p ) { if( *p>='0' && *p<='9' ) m = m*10 + (*p-'0'); else ret+=m, m=0; } ret += m; return ret; } int main( void ) { printf( "%u\n", foo("abc123def45gh678") ); return 0; }