2017-05-08 45 views
-1

我的代碼有問題。我需要在c中使用strtok()在字符串「Date WEEk Dae Due Toy De Dae i Date Due」中輸出單詞「Sing」和「Toy」(它們都在「Due」和「De」之間)唱德「。我試圖使用代碼中的if語句明確地輸出單詞「Sing」和「Toy」,但是我的代碼不會產生任何輸出,並且在編譯期間沒有警告。我只是C的初學者,請耐心等待。我聽說像strstr()這樣的其他函數可能能夠完成與strtok()相同的工作,所以如果其他函數使用起來更加方便,請不要猶豫,使用這些函數。謝謝。 摘要:我試圖在上面的字符串中使用strtok()來獲取「Due」和「De」之間的單詞,並且可以這樣做,還是應該使用另一個函數?如何使用strtok得到一個詞

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int main(){ 
char string[]="Date WEEk Dae Due Toy De Dae i Date Due Sing De"; 
char*pch; 
pch=strtok(string,"De"); 

while(pch!=NULL){ 
    if((*(pch-1)=='a')&&(*(pch-2)=='u')) 
    printf("%s\n",pch); 

    pch=strtok(NULL,"De"); 
} 
return 0; 
} 
+0

壓痕........................... – ThingyWotsit

+0

什麼是'由於結果唱歌德? 「唱歌」還是「唱歌」或者這不適用? – BLUEPIXY

回答

0

「如果你要打印唱歌,檢查是否PCH不是null,STRCMP(PCH,作爲第二個參數函數strtok

」星「)== 0然後打印星

你應該通過」
+0

這是針對strtok的第一個,第二個或兩個實例應該有「」作爲第二個參數嗎? – Antonio

0

查找 「由於」 後面有一個空格

char *due = strstr(string, "Due "); 

查找 「德」 前面有一個空格

char *de = strstr(string, " De"); 

檢查錯誤

if (!due || !de) exit(EXIT_FAILURE); 

打印內容是

+0

我試過你的解決方案,但我只有「玩具」而不是「玩具」和「唱歌」。 – Antonio

+0

我也用一個循環與計數器,但我只有「玩具」也。 – Antonio

+0

@Antonio從第二次開始,你需要在'de'之後開始。 – BLUEPIXY

1

之間

printf("%.*s\n", (int)(de - due - 4), due + 4); 
請記住的 strtok()第二個參數是一個分隔符列表:包含分隔符

C字符串字符。 這些可以從一個呼叫到另一個不同。

它們的方式現在在你的代碼中,令牌將在每個大寫D和小寫e之後進行。 對於您的描述中提到的案例,更適合使用strstr()來解決問題。

0

使用strstr這樣

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 

int main(void){ 
    char string[]="Date WEEk Dae Due Toy De Dae i Date Due Sing De"; 
    char *pre_word = "Due", *post_word = "De"; 
    size_t pre_word_len = strlen(pre_word), post_word_len = strlen(post_word); 
    char *p = string, *pre, *post; 

    while(pre = strstr(p, pre_word)){//find pre word 
     if((pre == string || isspace((unsigned char)pre[-1])) && 
      isspace((unsigned char)pre[pre_word_len])){//word check 
      if(post = strstr(pre + pre_word_len, post_word)){//find post word 
       if(isspace((unsigned char)post[-1]) && 
        (isspace((unsigned char)post[post_word_len]) || !post[post_word_len])){//word check 
        *post = 0;//The original string is changed 
        char word[32], dummy[2]; 
        if(1==sscanf(pre + pre_word_len, "%31s %1s", word, dummy)){//There is one word between words 
         printf("'%s'\n", word); 
        } 
       } 
       p = post + post_word_len;//set next search position 
      } else { 
       break;//Since post_word does not exist, it ends loop. 
      } 
     } 
    } 
    return 0; 
} 
+0

[DEMO](http://ideone.com/oDp9Ch) – BLUEPIXY

相關問題