2013-11-03 53 views
1

我一直在這個問題上困擾了很多年,我只是想不出一種方法來解決這個問題。 所以,我有一個數組,其中有一個條目列表,每個術語將與輸入文件進行比較,然後如果匹配,將會有一個輸出,其中會顯示「Match found」... 我有一個問題是strncasecmp只比較行的前n個字符。這意味着我必須每次都將陣列移動到最後。在一行中搜索一個術語

這是我想出了那麼遠,

while (fgets(line, 256, ifp) != NULL){ 
    for (i = 0; i < numberTerms; i++){ 
     len = strlen(term[i]); 
     for (lineStep = 0; lineStep < (strlen(line) - 1); lineStep++){ 
      if (line[lineStep] == '\0') 
       break; 
      if (strncasecmp(line, term[i], len) == 0) 
       printf("Match found!\n"); 
      for (j = 0; j < (strlen(line)-1); j++) 
       line[lineStep] = line[lineStep + 1]; 
     } 
    } 
} 

僅打印「匹配找到了!」一次而不是它需要的5次。我究竟做錯了什麼?另外,如果有更簡單的方式來搜索字符串,請讓我知道。

+1

嘗試'strcasetsr()' – technosaurus

+0

我不能,除非您發佈的信息,瞭解你的問題,這樣我可以重現你的結果。 –

+1

'strncasecmp()'只會比較該行的第一個「n」字符,如果將整行傳遞給它。如果你不是'line',而是''line [i]'這樣的東西,那麼你就不會這麼做。 –

回答

1

您可以使用函數strsstr查找另一個字符串內的子字符串。

這裏是一個示例用法:

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

int main(int argc, char** argv) 
{ 
    char* str = "hello foo world fOo this is foo a test foo strstr"; 
    char* p; 
    int offset = 0, len = strlen("foo"); 
    while((p = strstr(str+offset, "foo"))) { 
     printf("Match found at offset: %d\n", (p-str)); 
     offset = (p-str) + len; 
    } 
    return 0; 
} 

上面打印的代碼:

Match found at offset: 6 
Match found at offset: 28 
Match found at offset: 39 

還爲情況下不敏感的函數strcasestr但它不是標準。爲了使代碼便於攜帶,您可以編寫一個函數,將兩個字符串轉換爲小寫字母,然後使用strstr執行搜索。

編輯

這是一個基本功能將一個字符串變成小寫,返回的字符串需要是自由版!

#include <ctype.h> 

char* strtolower(char* str) 
{ 
    char* strlower = NULL, *p; 
    if(str) { 
     p = strlower = strdup(str); 
     while(*p) { 
      *p = tolower(*p); 
      p++; 
     } 
    } 
    return strlower; 
} 

使用上面的字符串和子串還應打印:

Match found at offset: 16 
相關問題