Given a character search for all occurrences of the character in the string and
ID: 3798144 • Letter: G
Question
Given a character search for all occurrences of the character in the string and print the character as well as the next 3 characters(hint: use substr for this). Create a function printChar for the above task. This function takes in two arguments- the string and the character and prints out the result on the screen. It returns no value.
Note: Make sure to cast your string length into integer before using it. i.e. use: (int) str.length()
Example: Given the string abracadabra and the character a, your output should be-
abra
acad
adab
abra
a
Explanation / Answer
#include <iostream>
#include <string.h>
using namespace std;
/*printChar function definition, function takes in two arguments- the string and the character */
void printChar(string str, char ch)
{
//print string
cout<<"String is : "<<str <<endl;
//use: (int) str.length()
int l=(int) str.length();
int i;
cout<<"Print the character as well as the next 3 characters "<<endl;
//using for loop find character
for(int i=0;i<l;i++)
{
// if char found in string then print substring
if(str[i]==ch)
{
cout << str.substr(i, 4) << endl;
}
}
}
// main
int main()
{
// string str
string str="abracadabra";
// char a
char ch='a';
//calling printchar function
printChar(str,ch);
return 0;
}//end of main
-------------------------------------
output sample:-
String is : abracadabra
Print the character as well as the next 3 characters
abra
acad
adab
abra
a
---------------------------------------------------------------------------------------------
If you have any query, please feel free to ask.
Thanks a lot.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.