2013-11-27 93 views
1

這裏尋找特定字符串是我的代碼:遇到問題在一個txt文件

int findKey(char *in, char *key, int buf){ 
int count = 0; 
FILE *f; 
f = fopen(in,"r"); 
char temp[buf]; 
while(fgets(temp,buf,f) != NULL){ 
    char *p = temp; 
    while((p=(strstr(p,key)))!=NULL){ 
     count++; 
     ++p; 
    } 
    int i = 0; 
} 
fclose(f); 
return count; 
} 

所以char *in是一個txt文件,關鍵是我要找的TXT文件中的一句話。因此,例如TXT文件可能是

hello Hello hello helloworld worldhello !hello! hello? hello, ?hello hello 

,如果關鍵詞是「你好」,再算上應該在這種情況下它返回9,因爲這還指望這些作爲有效返回2.然而:

helloworld worldhello !hello! hello? hello, ?hello 

時,它應該只算粗體爲有效

你好你好你好的HelloWorld worldhello!你好!你好?你好,?你好你好

我該如何解決這個問題?

+2

拆分使用'strtok_r()'空白字符的字符串,然後檢查每個子等於' 「你好」'。 – 2013-11-27 23:11:32

+0

'strtok_r'是一個GNU Libc擴展。 – randomusername

+0

@randomusername這不是一個GLibC擴展,它是POSIX ... – Macmade

回答

0

這個新例程的工作原理,可以很容易地擴展到" \n\r\t"(所有的空白字符)支持其他類型的分隔符。只要小心,因爲它使用動態分配,但它絕對是100%便攜式。

int count = 0; 
FILE *f = fopen (in, "r"); 
char *tmp = calloc (1, 1); 
int len = 0; 
while (! feof (f)) { 
    tmp = realloc (tmp, len + buf); 
    fgets (&tmp[len], buf, f); 
    len += buf; 
} 
fclose (f); 
strtok (tmp, ""); 
char *p; 
while ((p = strtok (NULL, " \n\r\t")) != NULL) 
    if (strcmp (p, key) == 0) 
    count += 1; 
free (tmp); 
return count; 
+0

我不允許修改輸入文件,只能從中讀取。 – user2923535

+0

試試這個技巧,它不會在緩衝區的開始時工作。 – randomusername

+0

這工作,但我如何讓它工作也在txt文件的開始? – user2923535

0

scanf()溶液:

兩種測試串和/或密鑰保持不變。 (const)。

void findKey(void) { 
    const char *in = 
      "hello Hello hello helloworld worldhello !hello! hello? hello, ?hello hello"; 
    const char *key = "hello"; 
    int count = 0; 
    char temp[strlen(in) + 1]; 
    const char *p = in; 
    while (*p) { 
    int n; 
    if (1 != sscanf(p, " %s%n", temp, &n)) { 
     break; 
    } 
    if (0 == strcmp(key, temp)) { 
     count++; 
    } 
    p = &p[n]; 
} 
printf("%d\n", count); 
} 
0

一個簡單的解決方案使用memcmp()isspace()

沒有臨時緩衝區需要

unsigned findKey(const char *in, const char *key) { 
    unsigned count = 0; 
    size_t keyLen = strlen(key); 
    int Ready = 1; 
    while (*in) { 
    while (isspace((unsigned char) *in)) { in++; Ready = 1; } 
    if (Ready) { 
     if (memcmp(in, key, keyLen) == 0 && 
      (isspace((unsigned char) in[keyLen]) || (in[keyLen] == '\0'))) { 
     count++; 
     } 
     Ready = 0; 
    } 
    in++; 
    } 
    return count; 
}