# Count occurrences of a character in a repeated string in C++

Given a string str, a character and a positive integer N. The string str is repeated indefinitely. The goal is to find the count of occurrences of character in str in first N characters of repetitions.

If str is “abac”, character is ch=‘b’ and N is 10.

In first 10 characters of “abacabacabacabac…….” b occurs twice.

Note − Take str and character ch within the same case.

Let us understand with examples.

For Example

## Input

str = "TPTTTT" ch = 'T' n = 12

## Output

Count of occurrences of a character in a repeated string are: 10

## Explanation

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.

## Input

str = "sets" ch = 's' n = 15

## Output

Count of occurrences of a character in a repeated string are: 7

## Explanation

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

Approach used in the below program is as follows

In this approach we will first count the number of occurrences of character ch in str. Then we will divide the length of str with N. We will get a number of full repetitions of str within N characters by (N / length of str). So, the number of occurrences of ch in those repetitions will be simple multiplication. For remaining characters (N % length of str) count ch in str again and add to previous count.

• Take a string str.

• Take n as integer, ch as character and length of str as integer.

• Function occurrences_char(string str, int length, int n, char ch) takes str, ch, n and length of str and returns the count of ch in first n characters in repeated string str.

• Take the initial count as 0.

• Using for loop count occurrences of ch in str. For each str[i]==ch, increment count.

• No of repetitions of str in n will be occ= n / length.

• No. of occurrences of ch in these repetitions will be count * occ.

• For remaining n % length characters of str check if str[i]==ch, if yes increment count.

• Return count as result.

## Example

Live Demo

#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;
}

## Output

If we run the above code it will generate the following output −

Count of occurrences of a character in a repeated string are − 10

Updated on: 05-Jan-2021

5K+ Views 