我有一个格式为联系人的字符串:
<abcde@123.343:5060;gr=xyz123>;+g134,<more_text>
我需要提取开头 <
之间的内容和关闭>
<
可以有多个实例和 >
, 但我必须从参数 gr=
的对中获取内容存在(仅出现一次)。
为了解决这个问题,我所做的是:
ptr = strstr(str,"gr=");
if(ptr)
{
temp1= ptr;
while(*temp1 && *temp1!='<')
{
temp1--;
}
strncpy(newstring,temp1,ptr-temp1); //will copy upto start of gr
temp2 = strstr(ptr,">")
if(temp2)
strncat(newstring,ptr,temp2-ptr); // copy remaining string till it finds closing '>'
}
它工作正常,但我想知道是否有任何方法可以避免 while 循环和倒退?
最佳答案
您可以搜索第一次出现的“<”和“>”,看看“gr=”是否在它们之间。
lt = strchr(ptr,'<');
gt = strchr(ptr,'>');
gr = strstr(ptr,"gr=");
if ( gr > lt && gr < gt) {
strncat(newstring,lt,gt-lt);
}
关于c - 更好地优化搜索字符串的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23830218/