2015-01-20 55 views
0

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

'为(J = 33;Ĵ<127; J ++)如果(字符串[I] == j)的算[D] ++;'可以被重写到刚刚'J =串[一世]; if(32 2015-01-20 20:57:46

+0

_I想尽可能多地使用现有的代码_您可以使用大部分代码。第一次通过后,你会计算每个角色的数量。现在用一个简单的方法找到数量最大的字符。 – 2015-01-20 21:06:22

+0

你将需要两个数组:'count [127]'和'best [127]'。当角色改变时,如果需要更新'best'数组。 – user3386109 2015-01-20 21:07:15

回答

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); 
} 
+0

什么是printf函数,它会在一行中显示最大数量的外观元素,然后呢? – Krowskir 2015-01-20 22:01:08

+0

@Krowskir进行编辑。我认为它现在应该工作。 – Matthew 2015-01-20 22:08:51

+0

@Krowskir不得不删除最后一部分。现在它应该只打印最大字符。 – Matthew 2015-01-20 22:10:09