Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวนครั้งที่ตัวอักษรปรากฏในสตริงซ้ำด้วย C++

ได้รับสตริง str, ตัวอักษร ch และจำนวนเต็มบวก N สตริง str จะถูกทำซ้ำไปเรื่อยๆ เป้าหมายคือหาจำนวนครั้งที่ตัวอักษร ch ปรากฏใน N ตัวอักษรแรกของสตริงที่ซ้ำกัน

ถ้า str = "abac", ch = 'b', N = 10

ใน 10 ตัวอักษรแรกของ "abacabacabacabac..." ตัวอักษร b ปรากฏ 2 ครั้ง

หมายเหตุ - ใช้ str และ ch ในเคสเดียวกัน (case-sensitive)

ตัวอย่าง

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

วิธีการที่ใช้ในโปรแกรม

วิธีนี้ก่อนอื่นนับจำนวนครั้งที่ตัวอักษร ch ปรากฏใน str แล้วหารความยาว str ด้วย N จะได้จำนวนรอบที่ str ทำซ้ำเต็มที่ภายใน N ตัวอักษรโดย (N / length of str) ดังนั้นจำนวนครั้งของ ch ในรอบเหล่านั้นจะเป็นการคูณง่ายๆ สำหรับตัวอักษรที่เหลือ (N % length of str) นับ ch ใน str อีกครั้งและบวกเข้ากับ count เดิม

  • รับสตริง str
  • รับ n เป็นจำนวนเต็ม, ch เป็นตัวอักษร และความยาว str เป็นจำนวนเต็ม
  • ฟังก์ชัน occurrences_char(string str, int length, int n, char ch) คืนค่าจำนวน ch ใน n ตัวอักษรแรกของ str ที่ซ้ำ
  • กำหนดจำนวนนับเริ่มต้นเป็น 0
  • ใช้ลูป for นับ ch ใน str สำหรับแต่ละ str[i]==ch เพิ่ม count
  • จำนวนรอบซ้ำของ str ใน n คือ occ = n / length
  • จำนวน ch ในรอบซ้ำเหล่านี้คือ count * occ
  • สำหรับตัวอักษรที่เหลือ n % length ตรวจสอบ str[i]==ch ถ้าใช่เพิ่ม count
  • คืนค่า count เป็นผลลัพธ์

ตัวอย่างโค้ด

#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

หากรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:

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