【问题标题】:Arrays and strpbrk in CC中的数组和strpbrk
【发布时间】: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


    【解决方案1】:

    首先,确保您正在使用的字符串在可修改的内存中1

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

    然后,在你找到&lt;的位置剪断你的字符串:

    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 数组,我们可以随意更改它。

    【讨论】:

    • 在要剪切的位置添加字符串终止符,如我的示例所示。
    • @user1558736 C 字符串以 '\0' 结尾。这意味着字符0 表示“字符串到此结束”。如果我有“abcdef”并将“c”替换为“\0”,我会得到字符串“ab”。这就是他对*pos = 0; 所做的事情
    • 是的,但是如果String_Buffer是长文本,现在我需要例如:“and i have”... 怎么知道位置?
    • 您可以从最后一个匹配位置之后的一个字符开始迭代此过程(跳过第一个 &gt; 之前的所有字符),但也许使用 strtok 可以更轻松地完成此操作。
    【解决方案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 > */
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      相关资源
      最近更新 更多