C++ 中统计并打印 ASCII 值不在 [l, r] 范围内的字母
给定任意长度的字符串,任务是计算并打印字符串中 ASCII 值不在 [l,r] 范围内的字母数量。
字符 A-Z 的 ASCII 值如下所示
| A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 |
| T | U | V | W | X | Y | Z |
|---|---|---|---|---|---|---|
| 84 | 85 | 86 | 87 | 88 | 89 | 90 |
字符 a-z 的 ASCII 值如下所示
| a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 9 7 | 9 8 | 9 9 | 10 0 | 10 1 | 10 2 | 10 3 | 10 4 | 10 5 | 10 6 | 10 7 | 10 8 | 10 9 | 11 0 | 11 1 | 11 2 | 11 3 | 11 4 | 11 5 |
| t | u | v | w | x | y | z |
|---|---|---|---|---|---|---|
| 116 | 117 | 118 | 119 | 120 | 121 | 122 |
例如
Input − String str = “point First = 111, Last = 117 Output − characters not in the given range are: i, n Count is: 2
解释 - 由于 i 和 n 不在 [111, 117] 的范围内,因此将统计这些字符。
Input − String str = “ABCZXY First = 65, Last = 70 Output − 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;
// To count the number of characters whose
// ascii value not in range [l, r]
int count_non_char(string str, int left, int right){
int count = 0;
// using map to print a character only once
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 the count
return count;
}
// main code
int main(){
string str = "tutorialspoint";
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP