在C ++中计算并打印ASCII值不在[l,r]范围内的字母
给我们一个任意长度的字符串,任务是计算计数并将字母打印在ASCII值不在[l,r]范围内的字符串中
字符AZ的ASCII值如下
下面给出了字符az的ASCII值
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
例如
Input − String str = “point
First = 111, Last = 117Output − characters not in the given range are: i, n
Count is: 2解释-由于i和n不在[111,117]范围内,因此将计算这些字符。
Input − String str = “ABCZXY
First = 65, Last = 70Output − characters in the given range are: A, B, C
Count is: 3解释-由于Z,X和Y不在[65,70]范围内,因此将对这些字符进行计数。
以下程序中使用的方法如下
输入字符串,开始和结束值以创建范围并将其存储在变量中,例如str。
使用该length()函数计算字符串的长度,该函数将根据字符串中包含空格的字母数返回一个整数值。
取得一个临时变量,该变量将存储字符数并创建一个映射,例如mp
从i到0开始循环,直到i小于字符串的长度
在循环内部,检查start是否小于等于str[i]和str[i]是否小于等于end
在if中,检查mp[str[i]]是否成功!=1,然后输出str[i],否则将mp[str[i]]增加1
返回计数
打印结果
示例
#include <iostream>
#include <unordered_map>
using namespace std;
//的字符数
//范围内
int count_non_char(string str, int left, int right){
int count = 0;
//使用映射仅打印一次字符
unordered_map<char, int> m;
int len = str.length();
for (int i = 0; i < len; i++) {
if (!(left <= str[i] and str[i] <= right)){
count++;
if (m[str[i]] != 1){
cout << str[i] << " ";
m[str[i]]++;
}
}
}
//返回计数
return count;
}
//主要代码
int main(){
string str = "nhooo";
int left = 102, right = 111;
cout << "Characters and ";
cout << "\nand count in the given range is: " << count_non_char(str, left, right);
return 0;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
Characters and and count in the given range is: t u r a s p 8