统计字符串中各个字符的个数

// 统计字符串中各字符的个数
#include "stdafx.h"
#include <stdio.h>     
#include <math.h>  
#include <iostream>
#include <String>
using namespace std;
int main()
{
loop1:
string key;
string delKey;
cout<<"Please input the string : ";
getline(cin,key);
int len = key.length();
for(int i = 0; i < len; i++)
{
int index = 0;
char c = key.at(i);

// 判断是否已经包含了此字符
int del_len = delKey.length();
bool b_same = false;
for(int k = 0; k < del_len; k++)
{
char del_c = delKey.at(k);
if(c == del_c)
{
b_same = true;
break;
}
}
if(b_same)
continue;
// 不包含的情况下,进行统计
delKey += c;
for(int j = 0; j < len; j++)
{
if(c == key.at(j))
index++;
}
cout<<c;
cout<<"'s number = "<<index<<endl;
}
char c_break;
cout <<"/n to over ? please input /" y /" :";
cin>>c_break;
if(c_break == 'y' || c_break == 'Y')
return 0;

goto loop1;
return 0;

}


// 统计字符串中各字符的个数, 方法二,号称要比方法1 简单很多~
#include "stdafx.h"
#include <stdio.h>     
#include <math.h>  
#include <iostream>
#include <String>
using namespace std;
int main()
{
int charNum[26];
for(int i =0; i<26; i++)
{
charNum[i] = 0;
}
string str;
cout<<"please input a string : "<<endl;
getline(cin,str);
int strLen = str.length();
for(int i=0; i < strLen; i++)
{
char s = str.at(i);
if(s >= 'A' && s <= 'Z')
{
int n = s - 'A';
charNum[n]++;
}
else if( s >= 'a' && s <= 'z')
{
int n = s - 'a';
charNum[n]++;
}
}
for(int i = 0; i< 26; i++)
{
char char_A = 'A' + i;
cout<<" the num of the char :"<<char_A<<" = "<<charNum[i]<<endl;
}
system("pause");
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值