O1 Write a complete and commented C++ program to find either: the index of a spe
ID: 3707429 • Letter: O
Question
O1 Write a complete and commented C++ program to find either: the index of a specified character in string OR the number of occurrences of a specified character in string using l the following header int count(const string &strl;, char chl) 1) For example (index), 2) For example (occurrences), countl("THello", "P) returns 2. Make sure that your program prompts the user to enter a string and a character. A special value count"welcome", 1) returns 2. (negative number) will terminate the input. Ctrl) "Explanation / Answer
Here is the required code you wanted. In the method count(), I have added code to find the index of a character in a string, and commented the code to find the count of the occurrence of a character. Go through it and let me know if you have any doubts. Thanks.
//code.cpp
#include<iostream>
using namespace std;
//method to find the index/count of a character ch1 in string str1
//please note that this method will do a case sensitive check
int count(const string &str1, char ch1){
//code to find the index of the character ch1 in string str1
for(int i=0;i<str1.length();i++){//looping through all characters
//checking if current character is the required character
if(str1[i]==ch1){
//returning the index
return i;
}
}
return -1; //not found
/* if you want to find the number of occurrences of character ch1
* in str1, comment the above lines of code,and uncomment below
* lines of code */
/*
int count=0;
for(int i=0;i<str1.length();i++){
if(str1[i]==ch1){
count++;
}
}
return count;
*/
}
int main(){
string input;
char c;
//looping until user enters -1
do{
cout<<"Enter a string (or -1 to quit): ";
cin>>input;
if(input!="-1"){
cout<<"Enter the character: ";
cin>>c;
//finding the index
int index=count(input,c);
if(index==-1){
//not found
cout<<"The entered character is not found in the list"<<endl;
}else{
//found
cout<<"The index of "<<c<<" in "<<input<<" is "<<index<<endl;
}
}
}while(input!="-1");
return 0;
}
/*OUTPUT*/
Enter a string (or -1 to quit): hello
Enter the character: l
The index of l in hello is 2
Enter a string (or -1 to quit): beautiful
Enter the character: f
The index of f in beautiful is 6
Enter a string (or -1 to quit): dummy
Enter the character: x
The entered character is not found in the list
Enter a string (or -1 to quit): -1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.