C++中統計並列印ASCII值在[l, r]範圍內的字母


給定任意長度的字串,任務是計算並列印字串中ASCII值在[l,r]範圍內的字母個數。

字元A-Z的ASCII值如下所示:

ABCDEFGHIJKLMNOPQRS
65666768697071727374757677787980818283


TUVWXYZ
84858687888990

字元a-z的ASCII值如下所示:

abcdefghijklmnopqrs
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


tuvwxyz
116117118119120121122

例如

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

更新於:2020年5月15日

269 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告