Day2
描述
写出一个程序,接受一个由字母、数字和空格组成的字符串,和一个字符,然后输出输入字符串中该字符的出现次数。(不区分大小写字母)
数据范围: 1 \le n \le 1000 \1≤n≤1000
输入描述:
第一行输入一个由字母、数字和空格组成的字符串,第二行输入一个字符(保证该字符不为空格)。
输出描述:
输出输入字符串中含有该字符的个数。(不区分大小写字母)
示例1
输入:
ABCabc
A
复制
输出:
2
思路:
- 思路1:直接直接编写大小写转换函数,转换思路:大写字母比小写字母小32,然后直接对字符串尽心遍历
复杂度
时间复杂度:Time:O(n) Space:O(n);
具体实现
#include <math.h>
#include <algorithm>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <stdlib.h>
#include <cstdlib>
#include <cstring>
//#include "./include/list/sqlist.h"
using namespace std;
//转换大小写算法
//根据ascii码进行转换,返回对应的转换后的ascii码
//asscii码相差32,根据asscii码表
//小写转换为大写
int LowerToUpper(char c){
int ans = 0;
if(c >= 'a' && c <= 'z') ans = c - 32;
return ans;
}
//大写转换为小写
int UpperToLower(char c){
int ans = 0;
if(c >= 'A' && c <= 'Z') ans = c + 32;
return ans;
}
//day2
//写出一个程序,接受一个由字母、数字和空格组成的字符串,和一个字符,然后输出输入字符串中该字符的出现次数。(不区分大小写字母)
//法1:暴力法
/**
* @description:
* @param {string} s
* @param {char} c
* @return {*}
*/
int CountSameCharater(string s, char c){
if(s.length() == 0) return 0;
int asscii_lower = 0;//记录转换的小写ascii码
int asscii_upper = 0;//记录转换的大写ascii码
//直接暴力正序遍历
int ans = 0;//出现的次数
//非迭代器遍历
//先将字符转换大小写
if(c >= 'a' && c <= 'c'){
asscii_upper = LowerToUpper(c);
asscii_lower = c;
}
else if(c >= 'A' && c <= 'Z'){
asscii_lower = UpperToLower(c);
asscii_upper = c;
}
else{
//不进行转换
asscii_lower = c;
asscii_upper = c;
}
//printf("%d",asscii_);
//printf("\n");
//顺序遍历字符串,输入字符进行匹配
for(int i = 0; i < s.length(); i++){
if(asscii_lower == s[i] || asscii_upper == s[i]) ans++;
}
return ans;
}
int main(){
string s;
//用到getline
getline(cin,s);//将输入流直接赋给s字符串
char c;
cin >> c;
int lastans = CountSameCharater(s,c);
printf("%d",lastans);
system("pause");
return 0;
}
小结
懂得用ascii码进行大小写转换,查询ascii码表