计算字符在数组中出现的次数? [英] count number of times a character appears in an array?

查看:169
本文介绍了计算字符在数组中出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想很长时间,没有任何地方的程序。我不知道从哪里开始。分配需要使用单个函数main和只使用iostream库。
任务是声明一个包含10个元素的char数组。从用户输入。确定数组是否包含任何值超过1次。

i've been thinking for a long time and havent got anywhere with the program. i dont know where to begin. The assignment requires use of single function main and only iostream library to be used. the task is to Declare a char array of 10 elements. Take input from user. Determine if array contains any values more than 1 times . do not show the characters that appears 1 time only.

Sample output:
a 2
b 4
..

a和b是字符。 2和4表示它们在数组B中出现的次数。

a an b are characters. and 2 and 4 represents number of times they appear in the array B.

我试图使用嵌套循环来比较一个字符与数组中的所有字符,并增加一个计数器

i tried to use nested loop to compare a character with all the character in array and incrementing a counter each time similer character id sound but unexpected results are occuring.

这里是代码

#include <iostream>
using namespace std;
void main()
{

    char ara[10];
    int counter=0;
    cout<<"Enter 10 characters in an array\n";
    for ( int a=0; a<10; a++)
        cin>>ara[a];

    for(int i=0;  i<10;  i++)
    {
       for(int j=i+1; j<10;  j++)
     {
         if(ara[i] == ara[j])
               {
                  counter++;
                  cout<<ara[i]<<"\t"<<counter<<endl;
               }
     }
    }
}


推荐答案

算法2:std :: map

声明/定义容器:

Algorithm 2: std::map
Declare / define the container:

std::map<char, unsigned int> frequency;




  1. 打开文件

  2. 读一封信。

  3. 找到这封信: frequency.find(letter)

  4. 频率:frequency [letter] ++;

  5. 如果字母不存在,请插入频率:frequency [letter] = 1;

  6. 处理完所有字母后,通过显示字母及其频率的地图

  1. Open the file
  2. read a letter.
  3. find the letter: frequency.find(letter)
  4. If letter exists, increment the frequency: frequency[letter]++;
  5. If letter no exists, insert into frequency: frequency[letter] = 1;
  6. After all letters processed, iterate through the map displaying the letter and its frequency.

这篇关于计算字符在数组中出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆