【发布时间】:2012-08-09 16:42:25
【问题描述】:
如果我的数组是:
char* String_Buffer = "Hi my name is <&1> and i have <&2> years old."
char* pos = strpbrk(String_buffer, "<");
现在位置是:
" 我已经 岁了。"
但我需要“嗨,我的名字是”。怎么会这样?
【问题讨论】:
标签: c
如果我的数组是:
char* String_Buffer = "Hi my name is <&1> and i have <&2> years old."
char* pos = strpbrk(String_buffer, "<");
现在位置是:
" 我已经 岁了。"
但我需要“嗨,我的名字是”。怎么会这样?
【问题讨论】:
标签: c
首先,确保您正在使用的字符串在可修改的内存中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 数组,我们可以随意更改它。【讨论】:
0 表示“字符串到此结束”。如果我有“abcdef”并将“c”替换为“\0”,我会得到字符串“ab”。这就是他对*pos = 0; 所做的事情
> 之前的所有字符),但也许使用 strtok 可以更轻松地完成此操作。
如果你单独跟踪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 > */
}
}
【讨论】: