在 C++ 中统计 ASCII 值之和小于和大于 k 的单词数量
给定一个包含句子的字符串 str 和一个数字 k。目标是找到 str 中 ASCII 值小于 k 的单词数量以及 ASCII 值大于 k 的单词数量。
ASCII - 赋予语言中每个字符的唯一代码数字。
让我们通过示例来理解。
输入 - str= “This is ASCII”。k=300
输出 - ASCII 值之和小于 k 的单词数量为 - 1
ASCII 值之和大于 k 的单词数量为 - 2
解释 - 单词“is”的 ASCII 值小于 300,其他两个也一样。
输入 - str= “set set set”。k=300
输出 - ASCII 值之和小于 k 的单词数量为 - 0
ASCII 值之和大于 k 的单词数量为 - 3
解释 - 所有单词都相同,并且 ASCII 值都大于 300。
下面程序中使用的方法如下
我们将使用 for 循环遍历字符串 str。对于空格后的每个单词,开始将 str[i] 添加到总和中。如果这 >k。增加计数。
将字符串作为 str,整数作为 k。
函数 words_less_greater(string str, int k, int length) 获取字符串并返回 ASCII 值小于和大于 k 的单词数量。
将 temp 设为 0,表示 str 中每个单词的 ASCII 值。
将 count 设为 0,表示 ASCII 值小于 k 的单词数量。
将 total 设为 0,表示 k 中的单词总数。
使用 for 循环遍历 str。
对于每个空格后的单词 str[i]==‘ ‘。将它的字符 str[i] 添加到 temp 中。在单词结束之后,检查 temp<k。如果是,则增加 count 和 total。
如果不是,则仅增加 total。
最后,count 包含 ASCII 值小于 k 的单词数量。total - count 将是 ASCII 值大于 k 的单词数量。
打印结果。
示例
#include <bits/stdc++.h> using namespace std; void words_less_greater(string str, int k, int length){ int temp = 0; int total = 0; int count = 0; for (int i = 0; i < length; ++i){ if (str[i] == ' '){ if (temp < k){ count++; } temp = 0; total++; } else{ temp += str[i]; } } total++; if (temp < k){ count++; } cout<<"Count of number of words having sum of ASCII values less than k are: "<< count; cout<<"\nCount of number of words having sum of ASCII values greater than k are: "<< total - count; } int main(){ string str = "tutorials point"; int k = 900; int length = str.length(); words_less_greater(str, k, length); return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果我们运行以上代码,它将生成以下输出 -
Count of number of words having sum of ASCII values less than k are: 1 Count of number of words having sum of ASCII values greater than k are: 1