C 计算行中出现的字符数
我写的程序是计算每个字母在字符串中出现的次数。我想改变它,它将找到在一行中出现大量次的字符,即对于字符串aabbbcccca,我想打印f c,因为一行中有四个c,只有两个a和三个b 如何改变我的程序,让它做我想做的事情?我正在寻找一个尽可能简单的解决方案,我希望尽可能多地使用现有的代码C 计算行中出现的字符数,c,C,我写的程序是计算每个字母在字符串中出现的次数。我想改变它,它将找到在一行中出现大量次的字符,即对于字符串aabbbcccca,我想打印f c,因为一行中有四个c,只有两个a和三个b 如何改变我的程序,让它做我想做的事情?我正在寻找一个尽可能简单的解决方案,我希望尽可能多地使用现有的代码 #include "stdafx.h" #include "string.h" #include "ctype.h" int count_nonspace(const char* str) { int
#include "stdafx.h"
#include "string.h"
#include "ctype.h"
int count_nonspace(const char* str)
{
int count = 0;
while (*str)
{
if (!isspace(*str++))
count++;
}
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[127];
int i = 0, j = 0, count[127] = { 0 };
char string[100] = "Hello world";
for (i = 0; i < strlen(string); i++)
{
for (j = 33; j<127; j++)
{
if (string[i] == (j))
{
count[j]++;
}
}
}
for (j = 0; j< 127; j++)
{
if (count[j] > 0)
if (j < ' ' + 1)
printf("\n%d -> %d", count[j], j);
else
printf("\n%d -> %c", count[j], char(j));
}
}
我更改代码的想法如下所示,仅发布更改的部分:
但结果仍然不如预期,这是为什么
for (i = 0; i < strlen(string); i++)
{
for (j = 33; j<127; j++)
{
if (string[i] == (j))
{
count[j]++;
if (string[i] == string[i + 1])
count[j]++;
else
best[j] = count[j];
}
}
}
对于j=33;jI希望尽可能多地使用现有代码,您可以使用大部分代码。第一次通过后,您将对每个字符进行计数。现在用一个简单的方法找到计数值最大的字符。您需要两个数组:计数[127]和最佳[127]。当字符更改时,如果需要,请更新最佳数组。@user3386109您能否进一步详细说明您的方法,因为给定字符串AACCCBBCA,我仍然不知道如何执行此操作。在索引2中,我们从'a'更改为'C',count['a']==2,因此将best['a']=2设置为best。在索引5中,我们有一个计数['C']=3的变化,所以设置best['C']=3。B的也一样。索引8是事情变得有趣的地方。从“C”到“a”有一个变化,但在这一点上,计数['C']==1和最佳['C']==3,所以保持最佳['C']=3。打印元素的printf函数是什么,一行中出现的次数最多?@Krowskir不得不删除最后一部分。现在,它应该只打印最大字符。谢谢,我一开始没有注意到,你是个天才。感谢你的帮助,非常感谢!我还有一个问题,如何改变这个程序,使它能够在文件而不是字符串上运行?@Krowskir我建议将文件读入字符串,然后在字符串上运行。以下是一个链接,指向如何执行此操作的问题:
#include "stdafx.h"
#include "string.h"
#include "ctype.h"
int count_nonspace(const char* str)
{
int count = 0;
while (*str)
{
if (!isspace(*str++))
count++;
}
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[127];
int i = 0, j = 0, count[127] = { 0 };
int cur_count = 1; /* Gets compared with value in count[] */
char cur_char = '\0';
char string[100] = "Hello world";
for (i = 0; i < strlen(string); i++)
{
if(cur_char == string[i])
{
cur_count++;
}
else
{
if(32 < cur_char && cur_char < 127)
{
if(cur_count > count[cur_char])
{
count[cur_char] = cur_count;
}
}
cur_char = string[i];
cur_count = 1;
if(32 < cur_char && cur_char < 127)
{
if(!(count[cur_char]))
{
count[cur_char] = cur_count;
}
}
}
}
/* Find the most consecutive char and print it. */
char max_char = '\0';
int max_count = 0;
for(j = 0; j < 127; j++)
{
if(max_count < count[j])
{
max_count = count[j];
max_char = j;
}
}
printf("%c\n", max_char);
}