我写的程序正在计算每个字母出现在字符串中的次数。我想改变它,它会发现连续出现很多次的字符,即字符串“aabbbcccca”我想printf“c”(因为有四个c在一行中,只有两个a和三个b)。计算连续的字符出现
如何改变我的程序,它会做我想要的东西?我正在寻找将尽可能简单的解决方案,并且我希望尽可能使用现有的代码。
#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;Ĵ<127; J ++)如果(字符串[I] == j)的算[D] ++;'可以被重写到刚刚'J =串[一世]; if(32
2015-01-20 20:57:46
_I想尽可能多地使用现有的代码_您可以使用大部分代码。第一次通过后,你会计算每个角色的数量。现在用一个简单的方法找到数量最大的字符。 – 2015-01-20 21:06:22
你将需要两个数组:'count [127]'和'best [127]'。当角色改变时,如果需要更新'best'数组。 – user3386109 2015-01-20 21:07:15