Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Check If a String is Made Up of Two Alternating Characters in C++



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
Updated on: 2019-09-27T07:43:32+05:30

407 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements