
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find repeated character present first in a string in C++
Suppose we have a string; we have to find first character that is repeated. So is the string is “Hello Friends”, the first repeated character will be l. As there are two l’s one after another.
To solve this, we will use the hashing technique. Create one hash table, scan each character one by one, if the character is not present, then insert into hash table, if it is already present, then return that character.
Example
#include<iostream> #include<unordered_set> using namespace std; char getFirstRepeatingChar(string &s) { unordered_set<char> hash; for (int i=0; i<s.length(); i++) { char c = s[i]; if (hash.find(c) != hash.end()) return c; else hash.insert(c); } return '\0'; } int main () { string str = "Hello Friends"; cout << "First repeating character is: " << getFirstRepeatingChar(str); }
Output
First repeating character is: l
- Related Articles
- Find the first repeated character in a string using C++.
- Find the first repeated word in a string in C++
- Count occurrences of a character in a repeated string in C++
- Find the first repeated word in a string in Python?
- Find the first repeated word in a string in Java
- Find the character in first string that is present at minimum index in second string in Python
- How to find the first character of a string in C#?
- Find the first repeated word in a string in Python using Dictionary
- Find the index of the first unique character in a given string using C++
- First Unique Character in a String in Python
- Swap For Longest Repeated Character Substring in C++
- How to find its first non-repeating character in a given string in android?
- Find one extra character in a string using C++.
- How to replace only the first repeated value in a string in MySQL
- Queries for characters in a repeated string in C++

Advertisements