计算连续出现的字符

时间:2015-01-20 20:53:10

标签: c

我编写的程序是计算每个字母出现在字符串中的次数。我想改变它,它会找到连续出现很多次的字符,即字符串" aabbbcccca"我想打印" 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];
        }
    }
}

1 个答案:

答案 0 :(得分:0)

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