我希望从特定字符串中获取所有数字,但是,这些数字可能超过一位数为(15,587,... exc)。这就是我所做的"我自己的代码":
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)。第一个电话是好的,但第二个电话不是&#34;无限循环&#34;值 index1:7 好吧 index2:0 不行!你能帮我把它搞定.....你
这些值由printf(..);
函数中的getNum();
打印....
答案 0 :(得分: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);
}