2016-11-13 2 views
0

특정 문자열에서 모든 숫자를 가져 오려고하지만 은 (15, 587, ... exc)와 같이 한 자리 이상 일 수 있습니다. 다음은 내가 직접 만든 코드입니다.C의 문자열에서 N 개의 숫자를 모두 추출하십시오

int firstIndxOfNumb(char* str, int startIndx, int len) { 
    int i, val; 
    i = startIndx; 
    while (str[i] && i < len) { 
     val = str[i]; 
     if (isdigit(val)) 
      return i; 
     i++; 
    } 
    return -1; 
} 

int lastIndxOfNumb(char* exp, int len, int indx1){ 
    int i, curr; 
    for(i = indx1; i < len; i++){ 
     curr = exp[i]; 
     if(!isdigit(curr)){ 
      return --i; 
     } 
    } 
    return 0; 
} 

int getNumb(char* exp, int len, int* indx1){ 
    int indx2 = lastIndxOfNumb(exp, len, *indx1); 

    printf("indx1:%d\tindx2:%d\n", *indx1, indx2); 

    char temp[indx2-*indx1]; 
    strncpy(temp, exp+*indx1, (size_t) (indx2-*indx1+1)); 
    *indx1 = firstIndxOfNumb(exp, indx2+1, len); 
    return atoi(temp); 
} 

void main() { 
    char *s = "())(15*59"; 
    int len = strlen(s); 
    int indx1; 
    indx1 = firstIndxOfNumb(s, 0, len); 
    printf("%d\n", getNumb(s, len, &indx1)); 
    printf("\n%d", getNumb(s, len, &indx1)); 

} 

목표는 두 개의 숫자 (15, 59)를 얻는 것입니다. 첫 번째 호출은 괜찮 았지만 두 번째 값은 "무한 루프"가 아니며 index1 : 7 괜찮음 index2 : 0은 좋지 않습니다! 당신은 ..... 내가 그것을 작동하게
값은 getNum(); 기능에 printf(..);로 인쇄됩니다 .... 다음과 같이

+0

'atoi'대신 'strtoi'를 사용할 수 있습니다. _and_ 읽은 문자 수를 반환합니다. 시간을 절약하십시오. –

+0

문자열에 음수가 없습니까? – BLUEPIXY

+0

@BLUEPIXY있다 –

답변

2

getNumb을 단순화 할 수 있도록 할 수 있습니다.

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

int getNumb(char **sp){ 
    char *p = *sp; 
    while(*p && !isdigit((unsigned char)*p))//skip not digit 
     ++p; 
    if(!*p) 
     return -1;//not find numbers (Don't include negative numbers as extract numbers) 
    int ret = strtol(p, &p, 10); 
    *sp = p; 
    return ret; 
} 

int main(void) { 
    char *s = "())(15*59"; 
    char *sp = s; 
    printf("%d\n", getNumb(&sp)); 
    printf("%d\n", getNumb(&sp)); 
} 

가 음수를 포함한다.

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

bool getNum(char **sp, int *v /* out */){ 
    char *p = *sp; 
    while(*p && !isdigit((unsigned char)*p) && (*p!='-' || !isdigit((unsigned char)p[1])))//skip not number 
     ++p; 
    if(!*p) 
     return false;//not find numbers 
    *v = strtol(p, &p, 10); 
    *sp = p; 
    return true; 
} 

int main(void) { 
    char *s = "())(15*59+++-123,-2)"; 
    char *sp = s; 
    int v; 
    while(getNum(&sp, &v)) 
     printf("%d\n", v); 
} 
+0

은 매우 단순합니다. –

관련 문제