用 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP