用 C++ 統計字串中 ASCII 值為素數的字元個數
給定一個任意長度的字串,包含大小寫字母,任務是計算其中 ASCII 值為素數的字元個數。
大寫字母 [A-Z] 的 ASCII 值從 65 到 90,小寫字母 [a-z] 的 ASCII 值從 97 到 122。
例如
Input string str = ‘Aebg’ Output count is: 2
說明 - 字元 A 的 ASCII 值為 65,不是素數,因此不會被計算;e 的 ASCII 值為 101,是素數,因此會被計算;b 的 ASCII 值為 66,不是素數,因此不會被計算;g 的 ASCII 值為 103,是素數,因此會被計算。因此,總共有 2 個字元的 ASCII 值為素數。
Input − string str = ‘GOXFH’ Output − count is: 2
說明 - 字元 G 的 ASCII 值為 71,是素數,因此會被計算;O 的 ASCII 值為 79,是素數,因此會被計算;X 的 ASCII 值為 88,不是素數,因此不會被計算;F 的 ASCII 值為 70,不是素數,因此不會被計算;H 的 ASCII 值為 72,不是素數,因此不會被計算。因此,總共有 2 個字元的 ASCII 值為素數。
下面程式中使用的方案如下
輸入字串並將其儲存在一個變數中,例如 str
使用 length() 函式計算字串 str 的長度,該函式將根據字串中字母的數量(包括空格)返回一個整數值。
宣告一個函式來計算素數值,我們將根據確定的每個字母對其進行檢查
遍歷迴圈,從 i=0 開始到字串長度
在迴圈內部,檢查遍歷到的字元的 ASCII 值是否為素數。如果是素數,則將計數增加 1,否則不增加值。
返回計數的總值
列印結果。
示例
#include <iostream> #include <vector> using namespace std; #define max_val 257 // Function to find prime characters in the string int countprime(string str){ // Using SIEVE for finding the prime numbers less // than Equal to 'max_val' // A Boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // 0 and 1 are not primes prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++){ // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Upfating the all multiples of p for (int i = p * 2; i <= max_val; i += p){ prime[i] = false; } } } int result = 0; // traversing the whole string. for (int i = 0; i < str.length(); ++i){ if (prime[int(str[i])]){ result++; } } return result; } // main function int main(){ string str = "tutorialspoint"; // print required answer cout <<"count is: "<< countprime(str); return 0; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
count is:1
廣告