java count unique characters in string

w‮ww‬.lautturi.com
java count unique characters in string

To count the number of unique characters in a string in Java, you can use a Set data structure to store the unique characters, and then return the size of the Set.

Here is an example of how you can do this:

public static int countUniqueCharacters(String s) {
    Set<Character> set = new HashSet<>();
    for (char c : s.toCharArray()) {
        set.add(c);
    }
    return set.size();
}

In this example, we have a method called countUniqueCharacters that takes a String as an argument. Inside the method, we create a new Set of type Character called set, and use a loop to iterate over the characters in the String. For each character, we add it to the Set using the add method. Finally, we return the size of the Set using the size method.

To use this method, you can call it like this:

int count = countUniqueCharacters("hello");

This will return the number of unique characters in the String "hello", which is 4 (h, e, l, o).

Created Time:2017-11-03 00:14:52  Author:lautturi