C提高_day03_作业第三题
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /*======================================================================================= 键值对(”key = valude”)字符串,在开发中经常使用; 要求1:请自己定义一个接口,实现根据key获取valude;40分 要求2:编写测试用例。30分 要求3:键值对中间可能有n多空格,请去除空格30分 注意:键值对字符串格式可能如下: “key1 = valude1” “key2 = valude2 “ “key3 = valude3” “key4 = valude4” “key5 = “ “key6 =“ “key7 = “ int getKeyByValude(char *keyvaluebuf, char *keybuf, char *valuebuf, int * valuebuflen); int main() { getKeyByValude(“key1 = valude1”, ” key1”, buf, &len); } ==========================================================================================*/ int trimSpace(char *str,char *newstr) { int ncount=0; int i=0,j=0; char *p=str; j=strlen(str)-1; if(str==NULL || newstr==NULL) { printf("fun trimSpace() \n"); return -1; } while(isspace(p[i]) && p[i]!='\0') { i++; } while(isspace(p[j]) && p[j]!='\0') { j--; } ncount=j-i+1; strncpy(newstr,str+i,ncount); //函数原型char *strncpy(char *dest, char *src, int n) //把src所指向的字符串中以src地址开始的前n个字节复制到dest所指的数组中,并返回dest newstr[ncount] ='\0'; return 0; } int getKeyByValue(char *keyvaluebuf,char *keybuf,char *valuebuf) { char *p=NULL; int ret=0; if(keyvaluebuf==NULL || keybuf==NULL || valuebuf==NULL) { return -1; } //1.查找key在不在母串中 p=keyvaluebuf; //初始化辅助指针变量 p=strstr(p,keybuf); if(p==NULL) { return -1; } //让辅助指针变量 重新达到下一次检索的条件 p=p+strlen(keybuf); //2.看有没有=号 p=strstr(p,"="); if(p==NULL) { return -1; } //让辅助指针变量 重新达到下一次检索的条件 p=p+strlen("="); //3.在等号后面去除空格 ret = trimSpace(p,valuebuf); if(ret!=0) { printf("func trimSpace() err:%d \n", ret); return ret; } return ret; } int main() { int ret=0; char buf[1024]={0}; char *keyandvalue = "key2 = valude2 "; char *key= "key2"; ret = getKeyByValue(keyandvalue,key,buf); if(ret!=0) { printf("func getKeyByValue() err:%d \n",ret); return ret; } printf("buf:%s \n",buf); system("pause"); return ret; }
Stay hungry,Stay foolish