Find the first repeated character in a string in Java
In this tutorial, we are going to write a program to find the first repeated character in a string in Java. In this problem, we need to find the first character that is repeated and not the most repeated character.
Let us see the basic steps to achieve our objective,
- Input the string that needs to be processed.
- Traverse the string and add each character in an ArrayList.
- Before adding the next character check if it already exists in the ArrayList.
If the character is present then it is the first repeated character. Print the first repeated character. - Otherwise, return false the string does not contain repeated characters.
This is an example of our problem,
Java Program: Find the first repeated character in a string
Let us see the Java program based on our steps,
import java.util.*; public class FindRepeatingChar { //Function to find repeated character static char findRepeat(char temp[]) { // Stores unique character in ArrayList ArrayList<Character> list = new ArrayList<>(); for (int i=0; i<=temp.length-1; i++) { char ch = temp[i]; // Checks for repeated character if (list.contains(ch)) return ch; //Adds unique character to the list else list.add(ch); } //Returns False in case of no repetition return 'F'; } public static void main (String[] args) { Scanner input = new Scanner(System.in); //String input System.out.println("Enter the String: "); String str = input.nextLine(); //string to char array for processing char[] charr = str.toCharArray(); //Prints in case of no repetition if (findRepeat(charr)=='F') System.out.println("NO REPETITION"); //Prints the repeated character else System.out.println("The First Repeated Character in the String is: "+findRepeat(charr)); } }
Output
- In the case of repeated character present in the string,
Enter the String: CODESPEEDY The First Repeated Character in the String is: E
- In the case of no repeated characters,
Enter the String: CODE NO REPETITION
You can also learn,
Leave a Reply