เราได้รับสตริงที่มีความยาวเท่าใดก็ได้ และภารกิจคือการคำนวณการนับและพิมพ์ตัวอักษรในสตริงที่มีค่า ASCII ในช่วง [l,r]
ค่า ASCII สำหรับอักขระ A-Z แสดงไว้ด้านล่าง
| A | B | C | D | E | F | G | สูง | ฉัน | J | K | L | ม | ไม่มี | 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 |
ค่า ASCII สำหรับอักขระ a-z แสดงไว้ด้านล่าง -
| ก | b | c | d | จ | f | g | ช | i | j | k | ล | ม | 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 จะน้อยกว่าความยาวของสตริง
-
ภายในลูป ตรวจสอบว่าเริ่มต้นน้อยกว่าเท่ากับ str[i] และ str[i] น้อยกว่าเท่ากับสิ้นสุด
-
ตอนนี้ เพิ่มจำนวนขึ้น 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