w3resource

C++ String Exercises: Check two consecutive, identical letters in a word

C++ String: Exercise-36 with Solution

Write a C++ program to check whether there are two consecutive (following each other continuously.), identical letters in a given string.

Test Data:
("Exercises") -> 0
("Yellow") -> 1

Sample Solution:

C++ Code:

#include <bits/stdc++.h>


using namespace std;

bool test(std::string word) {
  for(int i = 0; i < word.size()-1; i++){
    if(word[i] == word[i+1]){
      return true;
    }
  }
  return false;
}
int main()
{
	string text = "Exercises";
	cout << "Word: " << text;
	cout << "\nIf there are two consecutive identical letters in the said string?\n";
	cout << test(text) << endl;	 
	text = "Yellow";
	cout << "\nWord: " << text;
	cout << "\nIf there are two consecutive identical letters in the said string?\n";
	cout << test(text) << endl;	
}

Sample Output:

Word: Exercises
If there are two consecutive identical letters in the said string?
0

Word: Yellow
If there are two consecutive identical letters in the said string?
1

Flowchart:

Flowchart: Check two consecutive, identical letters in a word.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Reverse the words in a string that have odd lengths.

Next C++ Exercise: Count occurrences of a certain character in a string.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Ref: https://bit.ly/3niU71x