簡體   English   中英

斷開字符串指針直到c中的標記

[英]Breaking a string pointer till a marker in c

我有一個指針char * c =“我-需要-要做-這個-休息”。 我需要根據“-”將其斷開,以便在每次迭代中得到的輸出分別為“ I”,“ I -need”,“ I-need-to”,依此類推,直到整個字符串。 有什么幫助嗎?

簡單的方法是使c可變,而不是指向String Literal的指針。 這樣,您所需要做的就是處理字符串(使用指針或索引)並跟蹤您是否在單詞中。 當您打一個空格時(如果要刪除空格,則打連字符),如果您在單詞中,請保存當前字符,用'\\0'覆蓋數組中的當前字符以在當前字符處終止字符串,打印它。 恢復數組中的當前字符並重復執行,直到用完字符為止,例如

#include <stdio.h>

int main (void) {

    char c[] = "I - need - to - do - this - break", /* an array */
        *p = c;     /* pointer to current char */
    int in = 0;     /* flag for in/out of word */

    while (*p) {    /* loop over each char */
        if (*p == ' ' || *p == '-') {   /* if a space or hyphen */
            if (in) {                   /* if in a word */
                char current = *p;      /* save current char */
                *p = 0;                 /* nul-terminate array at current */
                puts (c);               /* print array */
                *p = current;           /* restore current in array */
                in = 0;                 /* set flag out of word */
            }
        }
        else {          /* otherwise, not a space or hyphen */
            in = 1;     /* set flag in word */
        }
        p++;            /* advance to next char */
    }

    if (in)             /* if in word when last char reached */
        puts (c);       /* output full string */
}

使用/輸出示例

$ ./bin/incremental
I
I - need
I - need - to
I - need - to - do
I - need - to - do - this
I - need - to - do - this - break

使用非可變字符串文字

如果必須使用不可更改的String Literal ,則方法基本相同。 唯一的區別是您不能對原始字符串進行n終止,因此您將使用另一個指針(或索引)從頭開始輸出每個字符,直到使用putchar到達當前字符為止(或者從p - c和然后復制到緩沖區以nul終止並立即全部輸出)。 簡單地循環直到達到電流並使用putchar進行輸出幾乎和其他任何事情一樣容易,例如

#include <stdio.h>

int main (void) {

    char *c = "I - need - to - do - this - break",  /* string literal */
        *p = c;     /* pointer to current char */
    int in = 0;     /* flag for in/out of word */

    while (*p) {    /* loop over each char */
        if (*p == ' ' || *p == '-') {   /* if a space or hypen */
            if (in) {                   /* if in a word */
                char *wp = c;           /* get pointer to start */
                while (wp < p)          /* loop until you reach current */
                    putchar (*wp++);    /* output each char & increment */
                putchar ('\n');         /* tidy up with newline */
                in = 0;                 /* set flag out of word */
            }
        }
        else {          /* otherwise, not a space or hyphen */
            in = 1;     /* set flag in word */
        }
        p++;            /* advance to next char */
    }

    if (in)             /* if in word when last char reached */
        puts (c);       /* output full string */
}

(輸出是相同的)

仔細檢查一下,如果您有任何問題,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM