现在的位置: 首页 > 综合 > 正文

提取字符串中的整数

2013年08月07日 ⁄ 综合 ⁄ 共 734字 ⁄ 字号 评论关闭

今天写了个,记在这:

#include <stdio.h>
#include <stdlib.h>

static int getNextInt( char* str, int *curp ) {
    int retInt = -1;
    int weight = 1;

    int num_begin, num_end;
    int pointer = *curp;

    num_begin = num_end = -1;
    
    if(str==NULL) return retInt;

    str = str+pointer;

    for(; *str != '\0'; str++, pointer++) {
        if( num_begin == -1 ) {
            if( *str >= '0' && *str <= '9' ) {
                num_begin = pointer;
                num_end = num_begin;
            }
            continue;
        } else {
            if( *str >= '0' && *str <= '9' )
                continue;
            num_end = pointer-1;
            break;
        }
    }
    
    if( num_begin == -1 ) return -1;

    *curp = pointer;
    retInt = 0;
    for(; num_end >= num_begin; num_end--, weight *= 10 ) {
        retInt += (*(--str) - '0') * weight;
    }

    return retInt;
}

int main( int argc, char **argv ) {
    if( argc != 2 ) {
        printf( "please use as getNextInt \"100 200 300\"\n" );
        exit(0);
    }

    int curp = 0;
    int res = -1;

    do {
        res = getNextInt( argv[1], &curp);
        printf("res = %d\n", res);
    } while ( res != -1 );

    return 0;
}
    

抱歉!评论已关闭.