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 in the given range are: p, o , t Count is: 3
说明 − 由于p、o和t在[111, 117]范围内,因此这些字符将被计数。
Input − String str = “ABCZXY First = 65, Last = 70 Output − characters in the given range are: A, B, C Count is: 3
说明 − 由于A、B和C在[65, 70]范围内,因此这些字符将被计数。
下面程序中使用的方案如下:
输入字符串,起始值和结束值以创建范围并将其存储在变量中,例如str。
使用length()函数计算字符串的长度,该函数将根据字符串中字母(包括空格)的数量返回一个整数值。
取一个临时变量来存储字符计数。
从i=0开始循环,直到i小于字符串长度。
在循环内,检查start是否小于等于str[i],以及str[i]是否小于等于end。
如果条件成立,则将计数增加1并打印str[i]。
返回计数。
打印结果。
示例
#include <iostream>
using namespace std;
// Function to count the number of
// characters whose ascii value is in range [l, r]
int count_char(string str, int left, int right){
// Initializing the count to 0
int count = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
// Increment the count
// if the value is less
if (left <= str[i] and str[i] <= right) {
count++;
cout << str[i] << " ";
}
}
// return the count
return count;
}
int main(){
string str = "tutorialspoint";
int left = 102, right = 111;
cout << "Characters in the given range";
cout << "\nand their count is " << count_char(str, left, right);
return 0;
}输出
如果运行以上代码,将生成以下输出:
Characters in the given range and their count is o i l o i n 6
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP