遇到问题在一个txt文件

问题描述:

这里寻找特定字符串是我的代码:遇到问题在一个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

这个新例程的工作原理,可以很容易地扩展到" \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

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); 
} 

一个简单的解决方案使用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; 
}