- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a given 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
#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
Advertisements