在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 in the given range are: p, o , t
Count is: 3解释-由于p,o和t在[111,117]范围内,因此将对这些字符进行计数。
Input − String str = “ABCZXY
First = 65, Last = 70Output − 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;
//函数计数数量
//范围内的字符
int count_char(string str, int left, int right){
//将计数初始化为0-
int count = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
//增加计数
//如果值小于
if (left <= str[i] and str[i] <= right) {
count++;
cout << str[i] << " ";
}
}
//返回计数
return count;
}
int main(){
string str = "nhooo";
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