Write a Java program to count unique Characters in string. Given a string as input, write Java code to count and print the number of unique characters in String. If there are no unique characters in the string, the method returns -1
Sample Input and Output
- Input consists of a string.
- The output consists of an integer.
Sample Input 1:
HOWAREYOU
Sample Output 1:
7
(Hint: Unique characters are: H, W, A, R, E, Y, U, and other characters are repeating)
Sample Input 2:
MAMA
Sample Output2:
-1
Count Unique Characters in String in Java
Following are the steps to count unique characters in a string in Java
- Input a string.
- Call the getCounts() method with the input string.
- Inside the method, first, convert the string into lowercase using the toLowerCase() method.
- Now, calculate the length using the length() method of StringBuffer and store it in a variable.
- Declare and initialize the count variable with 0.
- Now, iterate over the string and compare each char with the previous using two loops. If the character is matched then use the deleteCharAt() method and delete the char from the specified position.
- Increment the count value. Keep decrementing the index and length and repeat this process.
- Check if the count value is greater than 0, then once again delete char and decrement outer loop and length of the string.
- At last, check the length of the string. If the length is equal to 0 then return -1 else print the length of the string.
Java program to count Unique Characters in String
package com.company; import java.util.Locale; import java.util.Scanner; public class UniqueCharacterCount { public static void main(String[] args) { System.out.println("Enter String :"); Scanner scanner = new Scanner(System.in); String s1 = scanner.nextLine(); getCounts(s1); } private static void getCounts(String s1) { String s2 = s1.toLowerCase(); StringBuffer sb = new StringBuffer(s2); int l = sb.length(); int count = 0; for (int i = 0; i < l; i++) { count = 0; for (int j = i + 1; j < l; j++) { if (sb.charAt(i) == sb.charAt(j)) { sb.deleteCharAt(j); count++; j--; l--; } } if (count > 0) { sb.deleteCharAt(i); i--; l--; } } if (sb.length() == 0) { System.out.println(-1); } else System.out.println(sb.length()); } }
Output
In this way, we learn how to find the count of unique characters in a string in Java.