0

如果我的数组是:

char* String_Buffer = "Hi my name is <&1> and i have <&2> years old."
char* pos = strpbrk(String_buffer, "<");

现在 pos 是:

" <&1> 而我有 <&2> 岁。"

但我需要“嗨,我的名字是”。怎么能做到这一点?

4

2 回答 2

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)。


  1. 在您的代码中,您声明了一个char指针并使其指向一个不可修改的字符串文字(这就是您通常编写的原因;在这种情况下,相反,我们正在初始化一个本地数组,我们可以随意更改它.const char * str = "asdasads";char
于 2012-08-09T16:43:34.953 回答
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 > */
    }
}
于 2012-08-09T16:47:38.777 回答