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
廣告