<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+1
strncpy(newstr,str+i,count);//从str的第i个开始 拷贝count个字符
//newstr后面手工补0
newstr[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;
}
【C语言提高21】关于字符串的一个例题
最新推荐文章于 2024-11-25 21:55:27 发布
