怎样把字符串提取为数字
uint8_t ver[20]={0};uint8_t str[20]={0};
str[0] = 'v';
str[1] = '1';
str[2] = '.';
str[3] = '2';
str[4] = '.';
str[5] = '3';
str[6] = '.';
str[7] = '4';
怎样把str字符串提取为数字存到ver里面呢?
就是想要得到这样的效果ver[0]=1;ver[1]=2;ver[2]=3;ver[3]=4;
#include <stdio.h> int main( void ) { const char* str = "v1.2.3.4"; char ver[20]; char* q = ver; for( const char* p=str; *p; ++p ) if( *p>='0' && *p<='9' ) *q++ = *p; *q = '\0'; puts( ver ); }
#include <stdio.h> #include <stdint.h> int main( void ) { const char* str = "v1.2.3.4"; uint8_t ver[20]; size_t ver_size = 0; for( size_t p=0; ; ) { size_t len; int x = sscanf( str+p, "%hhu%zn", &ver[ver_size], &len ); if( x == EOF ) break; if( x == 0 ) ++p; else { p += len; ++ver_size; } } for( size_t i=0; i!=ver_size; ++i ) printf( "%hhu\n", ver[i] ); }
#include <stdio.h> #include <stdint.h> int main( void ) { const char* str = "v1.2.3.4"; uint8_t ver[4]; if( 4 == sscanf(str,"v%hhu.%hhu.%hhu.%hhu",ver+0,ver+1,ver+2,ver+3) ) printf( "%hhu %hhu %hhu %hhu", ver[0], ver[1], ver[2], ver[3] ); else puts( "格式错误" ); }
#include <stdio.h> #include <stdint.h> int main( void ) { const char* str = "v1.2.3.4"; uint8_t ver[20]; size_t ver_size = 0; for( size_t p=0; ; ) { size_t len = 0; sscanf( str+p, "%*[^0-9]%zn", &len ); p += len; int n = sscanf( str+p, "%hhu%zn", &ver[ver_size], &len ); if( n == EOF ) break; p += len; ++ver_size; } for( size_t i=0; i!=ver_size; ++i ) printf( "%hhu\n", ver[i] ); }
#include <stdlib.h> #include <string.h> void main() { int ver[20]={0}; char str[20]={0}; str[0] = 'v'; str[1] = '1'; str[2] = '.'; str[3] = '2'; str[4] = '.'; str[5] = '3'; str[6] = '.'; str[7] = '4'; str[8] = '5'; int i, j, k, flag; for (i=0; str[i]; i++) { if (str[i]<'1' || str[i]>'9') { str[i] = 0; } } for (j=k=flag=0; j<i; j++) { if (str[j]) { if (flag == 0) { ver[k++] = atoi(str+j); flag = 1; } } else { flag = 0; } } for (i=0; i<k; i++) { printf("%d ", ver[i]); } printf("\n"); }