C++中重复字符串中字符出现次数的计数
给定一个字符串str、一个字符ch和一个正整数N。字符串str无限重复。目标是找到在重复的第一个N个字符中字符ch出现的次数。
如果str是“abac”,字符是ch='b',N是10。
在“abacabacabacabac……”的前10个字符中,b出现两次。
注意 − str和字符ch保持相同的形式(大小写)。
让我们通过例子来理解。
例如
输入
str = "TPTTTT" ch = 'T' n = 12
输出
Count of occurrences of a character in a repeated string are: 10
解释
The number of ‘T’ in str is 5. Length of str is 6. For n=12, str will be fully repeated twice, so count of Ts is 6*2=12.
输入
str = "sets" ch = 's' n = 15
输出
Count of occurrences of a character in a repeated string are: 7
解释
The number of ‘s’ in str is 2. Length of str is 4. For n=15, str will be fully repeated 3 times (first 12 characters), so count of s in those will be 3*2=6. For the remaining 3 characters (set) s occurs once. So count is 6+1=7
下面程序中使用的方案如下 −
在这个方案中,我们将首先计算字符ch在str中出现的次数。然后我们将str的长度除以N。我们将通过(N / str的长度)得到str在N个字符内的完整重复次数。因此,ch在这些重复中的出现次数将是简单的乘法。对于剩余的字符(N % str的长度),再次计算str中ch的个数,并添加到之前的计数中。
取一个字符串str。
取n为整数,ch为字符,str的长度为整数。
函数occurrences_char(string str, int length, int n, char ch)接收str、ch、n和str的长度,并返回在重复字符串str的第一个n个字符中ch的计数。
将初始计数设为0。
使用for循环计算ch在str中出现的次数。对于每个str[i]==ch,递增计数。
str在n中的重复次数为occ= n / length。
ch在这些重复中的出现次数将是count * occ。
对于str剩余的n % length个字符,检查是否str[i]==ch,如果是,则递增计数。
返回计数作为结果。
示例
#include <bits/stdc++.h>
using namespace std;
int occurrences_char(string str, int length, int n, char ch){
int count = 0;
for (int i = 0; i < length; i++){
if (str[i] == ch){
count++;
}
}
int occ = n / length;
count = count * occ;
for (int i = 0; i < n % length; i++){
if (str[i] == ch){
count++;
}
}
return count;
}
int main(){
string str = "TPTTTT";
char ch = 'T';
int n = 12;
int length = str.size();
cout<<"Count of occurrences of a character in a repeated string are: "<<occurrences_char(str, length, n, ch);
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出:
Count of occurrences of a character in a repeated string are − 10
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP