Hi All,
Greetings of the day!
Today we will see how we can write a program in Java to find the first repeating character of a string, so let's start.
First, we will declare & initialize a String and then we will convert the String to a character array as shown below.
String testString="interview"; char[] charArray = testString.toCharArray();Now we will use HashSet to find the first repeating character from the String, so the basic logic is we will loop through each element of a character array and check if HashSet contains that character. If HashSet already contains that character it's a first repeating character and we will break our loop, else we will add a character to HashSet as shown below.
package com.demo.programs; import java.util.HashSet; import java.util.Set; public class FindFirstRepeatingCharacter { public static void main(String[] args) { String testString="interview"; char[] charArray = testString.toCharArray(); SetcharacterSet=new HashSet<>(); for(char c:charArray){ if(characterSet.contains(c)){ System.out.println("First repeating character is " +c); break; }else{ characterSet.add(c); } } } }
And O/P will be
First repeating character is i Process finished with exit code 0
If you face any challenges while implementing the above programs feel free to comment, we will try to help you.
Other articles you can refer
Sorting HashSet In Ascending & Descending order + Java 8
Comparator and Comparable In Java + Difference Between Comparator and Comparable + Java 8
Java 8 Stream - Intermediate Operations With Examples
Java 8 Stream - Terminal Operations With Examples
Thanks
Happy Learning!
0 Comments
If you have any doubts let me know.