【C语言提高21】关于字符串的一个例题

来源:互联网 发布:济宁网络教育报名 编辑:程序博客网 时间:2024/06/07 11:35
<span style="background-color: rgb(255, 255, 255);"><span style="color:#009900;">//*********************************************************////键值对(”key = valude”)字符串,在开发中经常使用;//要求1:请自己定义一个接口,实现根据key获取valude;40分//要求2:编写测试用例。30分//要求3:键值对中间可能有n多空格,请去除空格30分//注意:键值对字符串格式可能如下://“key1 = valude1”//“key2 = valude2//“key3 = valude3”   //“key4 = valude4”//“key5 = “//“key6 = “//“key7 = “//*********************************************************//</span></span>#include<stdlib.h>#include<stdio.h>#include<string.h>#include<ctype.h>//去除字符串的前后空格int trimSpace(char*str/*in*/,char*newstr/*in*/){char* p = str;int count = 0;if (str == NULL || newstr == NULL){return 0;}int i = 0;int j = strlen(p) - 1;while (isspace(p[i]) && p[i] != '\0'){i++;}while (isspace(p[j]) && p[j] != '\0'){j--;}count = j - i + 1;//7-1+1strncpy(newstr,str+i,count);//从str的第i个开始  拷贝count个字符        //newstr后面手工补0newstr[count] = '\0';return 1;}                //母串                  //字串                           int getKeyByValue(char*keyvaluebuf/*in*/, char*keybuf/*in*/){char*p = NULL;if (keyvaluebuf == NULL || keybuf == NULL){printf("err");return -1;}//1 查找子串key是不是在母串中//初始化辅助指针变量p = keyvaluebuf; p=strstr(p,keybuf);//返回str2在str1中首次出现的地址if (p == NULL){return -1;}//让辅助指针变量 重新达到下一次检索的条件p = p + strlen(keybuf);//p指向:"=       value2  "//2 有没有=号p = strstr(p,"=");if (p == NULL){return -1;}//让辅助指针变量 重新达到下一次检索的条件p = p + strlen("=");  //p指向:"       value2  "//3 在等号后面去除空格int ret = trimSpace(p, keybuf);if (ret != 0){printf("fun trim err");return ret;}return 0;}int main(){int ret = 0;char*keyandvalue = "key2 =       value2  ";char*        key = "key2";        ret=getKeyByValue(keyandvalue,key);if (ret != 0){printf("fun getKeyByValue err:%d",ret);return ret;}printf("buf is %s",key);system("pause");return 0;}

0 0
原创粉丝点击