Check if a given string is made up of two alternating characters in C++

C++Server Side ProgrammingProgramming

Here we will see how to check a string is made up of alternating characters or not. If a string is like XYXYXY, it is valid, if a string is like ABCD, that is invalid.

The approach is simple. We will check whether all ith character and i+2 th character are same or not. if they are not same, then return false, otherwise return true.

Example

 Live Demo

#include <iostream>
using namespace std;
bool hasAlternateChars(string str){
   for (int i = 0; i < str.length() - 2; i++) {
      if (str[i] != str[i + 2]) {
         return false;
      }
   }  
   if (str[0] == str[1])
   return false;  
   return true;
}
int main() {
   string str = "XYXYXYX";
   if(hasAlternateChars(str)){
      cout << "Valid String";
   }else{
      cout << "Not a Valid String";
   }
}

Output

Valid String
raja
Published on 27-Sep-2019 07:41:40
Advertisements