Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 반복되는 문자열의 문자 발생 횟수 계산


문자열 str, 문자 및 양의 정수 N이 주어지면 문자열 str은 무기한 반복됩니다. 목표는 반복의 처음 N 문자에서 str의 문자 발생 횟수를 찾는 것입니다.

str이 "abac"이면 문자는 ch='b'이고 N은 10입니다.

“아바카바카바카박…….”의 처음 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

아래 프로그램에서 사용된 접근 방식은 다음과 같습니다. -

이 접근 방식에서 우리는 먼저 str에서 문자 ch의 발생 횟수를 계산할 것입니다. 그런 다음 str의 길이를 N으로 나눕니다. N개의 문자 내에서 str의 완전한 반복 횟수를 (N / str의 길이)로 얻습니다. 따라서 이러한 반복에서 ch의 발생 횟수는 단순 곱셈이 됩니다. 나머지 문자(str의 N % 길이)의 경우 str의 ch를 다시 계산하고 이전 수에 추가합니다.

  • 문자열을 가져옵니다.

  • n을 정수로, ch를 문자로, str의 길이를 정수로 취합니다.

  • 함수 Occurrences_char(string str, int length, int n, char ch)는 ​​str, ch, n 및 str의 길이를 가져와서 반복되는 문자열 str에서 처음 n개 문자의 ch 개수를 반환합니다.

  • 초기 카운트를 0으로 합니다.

  • str에서 ch의 루프 카운트 발생을 사용합니다. 각 str[i]==ch에 대해 카운트를 증가시킵니다.

  • n에서 str이 반복되는 횟수는 occ=n / length가 됩니다.

  • 이 반복에서 ch의 발생 횟수는 count * occ가 됩니다.

  • str의 나머지 n % 길이 문자의 경우 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