用C计算文件中字符串的频率 [英] Calculating the frequency of a string in a file in C

查看:72
本文介绍了用C计算文件中字符串的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 while(fgets(temp1,512,my_file)!= NULL){
if((strstr(temp1,str))!= 0){
l ++;
printf(在线找到匹配:%d \ n,sr_num);
printf(\ n%s \ n,temp1);


结果++;
}



/ *这对于像mc Larenc,mc Cody,mc Larenc * /




我的尝试:



i需要检查频率字符串及其添加字符串的频率如mc Larenc,mc Cody,mc Larenc,mc Donell只检查前两个字符而不是整个字符串

解决方案

好的,我发现你的问题。您正在使用scanf获取要搜索的字符串,使用以下代码:

 printf( 输入您要搜索的名称\ n); 
scanf( %s,j);

result = Search_in_File( name.csv,j);



但是,scanf将空格视为标记分隔符,因此如果输入mc Larenc,它将仅提取mc部分作为要存储的值学家所以你在计算包含字符串mc的每个字符串。使用 strcmp 可能会帮助您更快地找到错误。


不要使用scanf(如已建议的那样),而是使用 gets_s,_getws_s | Microsoft Docs [ ^ ]这将读取完整的一行。



不要使用strstr,因为它不会完全比较。使用 strcmp,wcscmp,_mbscmp | Microsoft Docs [ ^ ](如已建议)。


while(fgets(temp1, 512, my_file) != NULL) {
if((strstr(temp1, str)) != 0) {
l++;
printf(" match found on line: %d\n", sr_num);
printf("\n%s  \n", temp1);


result++;
                }



/*this is returning same result  for strings like mc Larenc,mc Cody ,mc Larenc*/



What I have tried:

i need to check frequency of strings and its adding the frequency of strings like mc Larenc,mc Cody ,mc Larenc,mc Donell just checking first two characters not the whole string

解决方案

OK, I found your problem. You are using scanf to get the string to search for, with the following code:

printf("enter the name you want to search \n");
scanf("%s",j);

result = Search_in_File("name.csv", j);


BUT, scanf treats white space as a token separator, so if you enter "mc Larenc", it will only extract the "mc" part as the value to be stored in j. So you are counting each string that contains the string "mc". Using strcmp might have helped you find the mistake sooner.


Do not use scanf (as already suggested), instead use gets_s, _getws_s | Microsoft Docs[^] which will read a complete line.

Do not use strstr as it does not do a full compare. Use strcmp, wcscmp, _mbscmp | Microsoft Docs[^] (as already suggested).


这篇关于用C计算文件中字符串的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆