Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Check whether the characters e and g are separated by exactly 2 places anywhere in a given string at least once

C++ String: Exercise-6 with Solution

Write a C++ program to check whether the characters e and g are separated by exactly 2 places anywhere in a given string at least once.

Sample Solution:

C++ Code :

#include <iostream>

using namespace std;

bool Check_chars(string text) {

  int len = int(text.size());
  for (int i = 0; i < len; i++){
    if (text[i] == 'e' || text[i] == 'E'){
      if (i+2 < len  && (text[i+2] == 'g' || text[i+2] == 'G'))
          return true;
    }
    if (text[i] == 'g' || text[i] == 'G'){
      if (i+2 < len  && (text[i+2] == 'e' || text[i+2] == 'e'))
          return true;
    }
  }
  return false;

}

    int main() {
        cout << "Original string: eagerer -> " << Check_chars("eagerer") << endl;
        cout << "\nOriginal string: eaglets -> " << Check_chars("eaglets") << endl;
        cout << "\nOriginal string: eardrop -> " << Check_chars("eardrop") << endl;
        cout << "\nOriginal string: After eagling the Road Hole on Thursday, he missed an 8-footer for birdie Friday. -> ";
		cout << Check_chars("After eagling the Road Hole on Thursday, he missed an 8-footer for birdie Friday.") << endl;
        return 0;
}

Sample Output:

Original string: eagerer -> 1

Original string: eaglets -> 1

Original string: eardrop -> 0

Flowchart:

Flowchart: Check whether the characters e and g are separated by exactly 2 places anywhere in a given string at least once.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to sort characters (numbers and punctuation symbols are not included) in a string.
Next: Write a C++ program to count all the vowels in a given string.

What is the difficulty level of this exercise?