【发布时间】:2012-07-19 05:34:04
【问题描述】:
只是一个快速的:在 C 中,我有一个充满数据的缓冲区,如下所示:
char buffer[255]="CODE=12345-MODE-12453-CODE1-12355"
我的问题是如何搜索这个。例如对于CODE=12345,请记住数字会发生变化,所以我想在CODE= 部分之后使用通配符或预设数量的空格来搜索CODE=*****。
这个方法不会编译最后一个试试
#include <stdio.h>
#include <string.h>
#include <windows.h>
int main ()
{
char buf[255]="CODE=12345-MODE-12453-CODE1-12355";
#define TRIMSPACES(p) while(*p != '\0' && isspace((unsigned char)*p) != 0) ++p
#define NSTRIP(p, n) p += n
#define STRIP(p) ++p
char* getcode(const char *input)
{
char *p = (char*) input, *buf, *pbuf;
if((buf = malloc(256)) == NULL)
return NULL;
pbuf = buf;
while(*p != '\0') {
if(strncmp(p, "CODE", 3) == 0) {
NSTRIP(p, 4); //remove 'code'
TRIMSPACES(p);//trim white-space after 'code'
if(*p != '=')
return NULL;
STRIP(p); // remove '='
TRIMSPACES(p); //trim white-spaces after '='
/* copy the value until found a '-'
note: you must be control the size of it,
for avoid overflow. we allocated size, that's 256
or do subsequent calls to realloc()
*/
while(*p != '\0' && *p != '-')
*pbuf ++ = *p++;
// break;
}
p ++;
}
//put 0-terminator.
*pbuf ++ = '\0';
return buf;
}
//
}
【问题讨论】:
-
您真的是要在 CODE 后面加上 =,但在 MODE 和 CODE1 后面加上连字符吗?似乎不是一个一致的符号......