2016-05-30 32 views
2

我想在字符指針上找到strchr的第一個匹配項後又多出2個字符。該字符串可以是這樣的:前進指針並在strchr後獲得2個字符C

foo;bar;2012 -> should output foo;b 
foo;caz;  -> should output foo;c 
foo;   -> should output foo (there are no +2 chars) 
foo   -> null 

對於第一種情況,我想我可以這樣做,

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

int main() 
{ 
    char str[] = "foo;bar;2012"; 
    char *pch = NULL; 

    if ((pch=strchr(str,';')) != NULL) { 
    *pch++; 
    *pch++; 
    *pch = '\0'; 
    } 
    puts(str); 
    return 0; 
} 

但是,什麼是檢查,如果我能在字符串中前進的指針沒有的正確方法過去?

+1

如果您需要處理超過2個字符,或它們的任意號碼,然後使用strlen(STR)來獲取長度。之後,你可以用str + len創建一個結束指針來與pch進行比較,或者你可以通過pch-str找到你的索引來與len進行比較。然後你減去找到字符串末尾有多少個字符。 –

+0

@ZanLynx謝謝,很高興知道這一點。 –

+0

嘗試更改每個'* pch ++;'到'if(* pch)pch ++;' – Dmitri

回答

3

*pch++行應該生成一個編譯器警告(如果他們不這樣做,你沒有編譯時啓用了足夠的警告)。我編譯視爲錯誤的警告,所以我得到:

xw31.c:10:5: error: value computed is not used [-Werror=unused-value] 
    *pch++; 

您應該使用pch++; - 不讀卻忽略了價值。

你應該檢查訪問超出地方strstr()點你,而你還沒有達到字符串的結尾,所以可以使用:

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

int main(void) 
{ 
    char str[] = "foo;bar;2012"; 
    char *pch; 

    if ((pch = strchr(str, ';')) != NULL) 
    { 
     if (pch[1] != '\0' && pch[2] != '\0') 
      pch[3] = '\0'; 
     puts(str); 
    } 
    return 0; 
} 

如果內部測試失敗,該字符串是足夠短了。當然,pch[0]是分號。這會生成foo;ba作爲輸出。如果你只想foo;b,那麼你只需要測試一個字符領先少:

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

int main(void) 
{ 
    char str[] = "foo;bar;2012"; 
    char *pch; 

    if ((pch = strchr(str, ';')) != NULL) 
    { 
     if (pch[1] != '\0') 
      pch[2] = '\0'; 
     puts(str); 
    } 
    return 0; 
} 
+0

謝謝,我現在明白了。我不確定檢查下一個字符'[1]'是否安全。 –

+0

考慮到你以一個(以null結束的)字符串開始,你知道在分號後至少有一個字節是安全的。顯示的代碼檢查是否可以繼續前進。它有時可能會用另一個覆蓋空字節。 –