如果我的数组是:
char* String_Buffer = "Hi my name is <&1> and i have <&2> years old."
char* pos = strpbrk(String_buffer, "<");
现在pos是:
“&lt;&amp; 1&gt;并且我已经&lt;&amp; 2&gt;岁了。”
但我需要“嗨,我的名字是”。怎么办呢?
答案 0 :(得分:3)
首先,确保您使用的字符串位于可修改的内存中 1 :
char String_Buffer[] = "Hi my name is <&1> and i have <&2> years old."
然后,在找到<
:
char* pos = strpbrk(String_buffer, "<");
if(pos!=NULL)
{
/* changing the '<' you found to the null character you are actually
* cutting the string in that place */
*pos=0;
}
打印String_Buffer
现在将输出Hi my name is
。如果你不想要最后的空格,只需向后移动pos
一个元素(注意不要在String_Buffer
的开头之前)。
char
指针,并指向一个字符串文字,这是不可修改的(这就是你通常写 const
的原因 char * str = "asdasads";
;在这种情况下,我们正在初始化一个本地char
数组,我们可以根据需要进行更改。答案 1 :(得分:2)
如果您单独跟踪start
,则可以“剪切”缓冲区的一部分:
char *start = String_Buffer;
char *end = strpbrk(String_Buffer, "<");
if (end) {
/* found it, allocate enough space for it and NUL */
char *match = malloc(end - start + 1);
/* copy and NUL terminate */
strncpy(match, start, end - start);
match[end - start] = '\0';
printf("Previous tokens: %s\n", match);
free(match);
} else {
/* no match */
}
要遍历缓冲区打印每个令牌,您只需将其提升到循环中:
char *start = String_Buffer, *end, *match;
while (start) {
end = strpbrk(start, "<");
if (!end) {
printf("Last tokens: %s\n", start);
break;
} else if (end - start) {
match = malloc(end - start + 1);
/* copy and NUL terminate */
strncpy(match, start, end - start);
match[end - start] = '\0';
printf("Tokens: %s\n", match);
free(match);
end++; /* walk past < */
}
/* Walk to > */
start = strpbrk(end, ">");
if (start) {
match = malloc(start - end + 1); /* start > end */
strncpy(match, end, start - end);
match[start - end] = '\0';
printf("Bracketed expression: %s\n", match);
free(match);
start++; /* walk past > */
}
}