计算字符在数组中出现的次数? [英] count number of times a character appears in an array?
问题描述
我一直在想很长时间,没有任何地方的程序。我不知道从哪里开始。分配需要使用单个函数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;
- 打开文件
- 读一封信。
- 找到这封信:
frequency.find(letter)
- 频率:frequency [letter] ++;
- 如果字母不存在,请插入频率:frequency [letter] = 1;
- 处理完所有字母后,通过显示字母及其频率的
地图
- Open the file
- read a letter.
- find the letter:
frequency.find(letter)
- If letter exists, increment the frequency: frequency[letter]++;
- If letter no exists, insert into frequency: frequency[letter] = 1;
- After all letters processed, iterate through the
map
displaying the letter and its frequency.
这篇关于计算字符在数组中出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!