计算字符个数

来源:互联网 发布:电脑双桌面软件 编辑:程序博客网 时间:2024/06/05 18:56

题目描述

写出一个程序,接受一个有字母和数字以及空格组成的字符串,和一个字符,然后输出输入字符串中含有该字符的个数。区分大小写。

输入描述:

输入一个有字母和数字以及空格组成的字符串,和一个字符。

输出描述:

输出输入字符串中含有该字符的个数。

实例

输入

ABCDEF

A

输出

1

代码:

#include <iostream>

#include <string.h>

#include <stdlib.h>

using namespace std;

int main(){

char str[10000];

cin>>str;

char s;

cin>>s;

int count = 0;

int length = strlen(str);

for(int k = 0;k<length;k++){

if(s==str[k])

count++;

}

cout<<count<<endl;

return 0;

}

要是题目改成不区分大小写,改如何???

#include <iostream>

#include <string.h>

using namespace std;

int main(){

string input;

char s;

getline(cin,input);

cin>>s;

char temp;

if(s>= 65&&s<=96)

temp = s+32;

if(s>= 97&&s<=129)

temp = s-32;

int count = 0;

for(int i = 0;i<input.length();i++){

if(input[i]==s||input[i] == temp)

count++;

}

cout <<count<<endl;

return 0;

}