find the number of times a character occurs between two indexes

try this:

#include <iostream>
#include <cstring>
#include <iostream>
#include <string>
#include <string.h>

using namespace std;

int main()
{
    char inputString[11];
    int b_in_string, b_occurrence, repetitions, startIndex, endIndex, actual_needed_count;

    cout<<"Input string: ";
    cin>>inputString;
    cout<<"Repetitions: ";
    cin>>repetitions;
    cout<<"Start index: ";
    cin>>startIndex;
    cout<<"End index: ";
    cin>>endIndex;

    if(endIndex < startIndex)
    {
        cout<<"End index must be larger than start index. Program terminated.";
        return 1;
    }

    b_in_string = 0;
    b_occurrence = 0;

    for(int i = 0; i < sizeof(inputString); i++)
    {
        if(inputString[i] == 'b')
        {
            b_in_string++;
        }
    }

    actual_needed_count = endIndex - startIndex + 1; //start and end indexes inclusive

    b_occurrence = b_in_string * actual_needed_count;

    cout<<"Number of times 'b' occurs: ";
    cout<<b_occurrence;

    return 0;
}

It works on https://www.onlinegdb.com/online_c++_compiler. Hope it helps.

Browse More Popular Posts

Leave a Comment