简体   繁体   English

C中的数组和strpbrk

[英]Arrays and strpbrk in C

If my array is : 如果我的数组是:

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

Now pos is : 现在pos是:

" <&1> and i have <&2> years old. " “ <&1>并且我已经<&2>岁。”

But i need "Hi my name is". 但是我需要“嗨,我叫”。 How can do this? 怎么办

First, make sure that the string you are working with is in modifiable memory 1 : 首先,请确保您正在使用的字符串在可修改的内存1中

char String_Buffer[] = "Hi my name is <&1> and i have <&2> years old."

then, cut your string at the position where you found < : 然后,在找到<的位置剪切字符串:

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;
}

Printing String_Buffer will now output Hi my name is . 打印String_Buffer现在将输出Hi my name is If you don't want the final space, just move pos backward of one element (being careful not to go before the beginning of String_Buffer ). 如果您不想要最后一个空格,只需将pos向后移一个元素(注意不要移到String_Buffer的开头)。


  1. In your code you declared a char pointer and made it point to a string literal, which is non-modifiable (that's why you normally write const char * str = "asdasads"; ; in this case, instead, we are initializing a local char array, which we can change as much as we want. 在您的代码中,您声明了一个char指针,并将其指向不可修改的字符串文字(这就是您通常编写const char * str = "asdasads"; ;在这种情况下,我们正在初始化本地char数组,我们可以根据需要进行任意更改。

If you track start separately, you can "cut out" a section of the buffer: 如果单独跟踪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 */
}

To walk the buffer printing each token, you'll simply hoist this into a loop: 要遍历打印每个令牌的缓冲区,只需将其提升为循环:

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 > */
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM