C语言提取字符串
在只给<stdio.h>和<string>头文件的情况下,从下文中提取UserId=123456
https://www.cnblogs.com/ysjd UserId=123456 passwd=513920
代码如下:
1 #include<stdio.h> 2 #include<string.h> 3 4 int myatoi(char str[]) 5 { 6 int len=strlen(str); 7 char *p=str+len-1; 8 int sum=0,i=0,num; 9 while(p>=str) 10 { 11 num=*p-48; 12 for(int j=0;j<i;j++) 13 { 14 num*=10; 15 } 16 i++; 17 sum+=num; 18 p--; 19 } 20 return sum; 21 } 22 23 int getUserId(char *p,int *n) 24 { 25 char *q=strstr(p,"UserId="); 26 if(q==NULL) 27 return 0; 28 q+=7; 29 char str[20]; 30 int i=0; 31 while(*q>='0' && *q<='9') 32 { 33 str[i]=*q; 34 i++; 35 q++; 36 } 37 str[i]='\0'; 38 *n=myatoi(str); 39 return 1; 40 } 41 int main() 42 { 43 char str[]="https://www.cnblogs.com/ysjd UserId=123456 passwd=513920"; 44 int n; 45 int ret=getUserId(str,&n); 46 if(ret==0) 47 { 48 printf("not found\n"); 49 } 50 else 51 { 52 printf("UserId=%d\n",n); 53 } 54 }