查找位于素数位置的字符的ASCII值之和
介绍
在本教程中,我们将学习C++的概念,以查找位于素数位置的字符的ASCII值之和。素数位置是指位置为2、3、5或其他素数的字符。
ASCII(美国信息交换标准代码)值为字母、数字、标点符号和其他字符在编码中使用的唯一数值。它用于与计算机通信,因为计算机不理解人类语言。
共有128个ASCII值,从0到127。大写字母和小写字母具有不同的ASCII值。
我们将开发一个C++代码来计算位于素数位置的字符的ASCII值。我们使用字符串类的length()函数来存储输入字符串的长度。
示例1
There is an string = “Hello” Sum of prime position ASCII value characters = 320
In the above string “Hello” the ASCII value of each character is H = 72 e = 101 l = 108 l = 108 o = 111
位于素数位置的字符是“e”、“l”、“o”。添加这些素数位置字符的ASCII值。
示例2
Input string = “abcd” Sum = 197
输入字符串“abcd”中位于素数位置的字符是“b”和“c”。
The ASCII value of input string characters is as listed: a = 97 b = 98 c = 99 d = 100
计算字符串中位于素数位置的字符的ASCII值之和。
语法
sqrt() − 此库函数在math库中定义,它返回输入数字的平方根。
sqrt(n)
length() − 此字符串类库函数返回输入字符串的长度,长度是字符串中字符的数量。
string_name.length();
示例1
我们将使用C++编程语言实现一个示例,以计算输入字符串中位于素数位置的字符的ASCII值之和。C++代码输入字符串为“Hello”。我们首先通过应用识别素数的逻辑来查找输入字符串的所有素数位置。使用for循环查找输入字符串所有字符的ASCII值。将位于素数位置的输入字符串字符的ASCII值相加。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// User-defined function to find the prime positions
bool find_prime(int p){
if (p <= 1) {
return false;
}
// loop to check the prime number
for (int x = 2; x*x <= p; x++) {
if (p % x == 0) {
return false;
}
}
return true;
}
// user-defined function to sum ASCII values of the prime position characters
int sum_of_primes(string st) {
int sum1 = 0;
//variable to store the input string length.
int p = st.length();
vector<bool> primes(p+1, false);
primes[2] = true;
for (int x = 3; x <= p; x += 2) {
primes[x] = find_prime(x);
}
for (int x = 2; x <= p; x++){
if (primes[x] && x <= p){
sum1 += int(st[x-1]);
}
}
return sum1;
}
// controlling code
int main(){
string st = "Hello";
int sum1 = sum_of_primes(st);
cout << "Sum of ASCII values of characters at prime positions: " << sum1 << endl;
return 0;
}
输出
"Sum of ASCII values of characters at prime positions: 320
示例2
在这里,我们使用不同的逻辑来实现此示例。我们首先找到素数位置,然后在main()中找到这些ASCII值并将其相加。
#include <iostream>
#include <cmath>
using namespace std;
bool isNumPrime(int n) {
if (n < 2)
return false;
for (int x = 2; x <= sqrt(n); ++x) {
if (n % x == 0)
return false;
}
return true;
}
int main() {
string str = "tutorialspoint";
//std::cout << "Enter a string: ";
int s = 0;
for (size_t x = 0; x < str.length(); ++x) {
if (isNumPrime(x + 1)) {
s += static_cast<int>(str[x]);
}
}
cout << "Sum of ASCII values at prime positions: " << s << endl;
return 0;
}
输出
Sum of ASCII values at prime position: 665
结论
在本教程中,我们开发了C++代码来查找素数位置字符的ASCII值之和。我们使用字符串类的length()函数来查找参数字符串的长度。ASCII值是字母和其他字符的预定值,以帮助计算机进行通信。在本教程中,我们使用不同的逻辑实现了两个示例,并使用了一些C++库函数。使用的最重要的库函数是length()。此length()库函数返回字符串的长度。
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP