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