gpt4 book ai didi

计算连续出现的字符

转载 作者:行者123 更新时间:2023-11-30 17:22:17 24 4
gpt4 key购买 nike

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

最佳答案

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

关于计算连续出现的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com