+92 332 4229 857 99ProjectIdeas@Gmail.com

Counting each alphabet in a string (C++)


How to count each alphabat
The code given below counts and prints each alphabet occurring in the string.

Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

int main()
{
char str[50]="Hello my name is Saad Bin Saulat";
int length=0;
int count[26]={0};

for(int i=0;str[i]!='\0';i++)
{
switch(str[i])
{
case 'A':
case 'a':{++count[0];break;}
case 'B':
case 'b':{++count[1];break;}
case 'C':
case 'c':{++count[2];break;}
case 'D':
case 'd':{++count[3];break;}
case 'E':
case 'e':{++count[4];break;}
case 'F':
case 'f':{++count[5];break;}
case 'G':
case 'g':{++count[6];break;}
case 'H':
case 'h':{++count[7];break;}
case 'I':
case 'i':{++count[8];break;}
case 'J':
case 'j':{++count[9];break;}
case 'K':
case 'k':{++count[10];break;}
case 'L':
case 'l':{++count[11];break;}
case 'M':
case 'm':{++count[12];break;}
case 'N':
case 'n':{++count[13];break;}
case 'O':
case 'o':{++count[14];break;}
case 'P':
case 'p':{++count[15];break;}
case 'Q':
case 'q':{++count[16];break;}
case 'R':
case 'r':{++count[17];break;}
case 'S':
case 's':{++count[18];break;}
case 'T':
case 't':{++count[19];break;}
case 'U':
case 'u':{++count[20];break;}
case 'V':
case 'v':{++count[21];break;}
case 'W':
case 'w':{++count[22];break;}
case 'X':
case 'x':{++count[23];break;}
case 'Y':
case 'y':{++count[24];break;}
case 'Z':
case 'z':{++count[25];break;}
}
}

for(int j=0;j<26;j++)
cout<<char(j+97)<<"-"<<count[j]<<endl;

_getche();
return 0;
}
Ouptut
a-5
b-1
c-0
d-1
e-2
f-0
g-0
h-1
i-2
j-0
k-0
l-3
m-2
n-2
o-1
p-0
q-0
r-0
s-3
t-1
u-1
v-0
w-0
x-0
y-1
z-0

0 comments: