Count duplicate characters in a string in Java without using Collection or HashMap or Set



 Write a Java program to find duplicate characters in a string without Hashmap and Set.

Java program to count duplicate characters

public class Main {

	public static void main(String[] args) {
		
		String str = "Java is my fav programming language. I love Java coding";
		
		System.out.println("Duplicates in- " + str);
		int count;
		for (int i = 0; i < str.length(); i++) {
			count = 1;
			// Take one char at a time
			char c = str.charAt(i);
			// don't count the spaces
			if (c == ' ')
				continue;
			for (int j = i + 1; j < str.length(); j++) {
				if (c == str.charAt(j)) {
					count++;
					// remove the char so that it is not picked again
					// in another iteration
					str = str.substring(0, j) + str.substring(j + 1);
				}
			}
			if (count > 1) {
				System.out.println(c + " found " + count + " times");
			}
		}
	}
}

Output:

Duplicates in- Java is my fav programming language. I love Java coding
J found 2 times
a found 8 times
v found 4 times
i found 3 times
m found 2 times
r found 2 times
o found 3 times
g found 5 times
n found 3 times
l found 2 times
e found 2 times

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments