Search code examples
javarepeater

How to count the number of letters that exist without repeated


I want a way to count the letters in an string for example:

My string : "Hello my friends "

The characters in the string : {H,e,l,o, ,m,y,f,r,i,n,d,s}

These letters exist without repeating them (with a blank space) So the result I want is: 13

The goal of all of this is, I want to convert a string to a table of character without repeating the letters

EX: MY String = "Hello"

The table I want to get {H,e,l,o}

My attempt

 public static int numberRep(String txt) {
    int count = 0;
        boolean v = false;
        for (int i = 0; i != txt.length(); i++) {
            char c = txt.charAt(i);
            for (int j = i + 1; j != txt.length(); j++) {
                if (txt.charAt(j) == c) {
                    count++;
                }
            }
            if(count == txt.length()-1){
                v = true;
            }
        }
        if(v){
            return 1 ;
        }
        else{
        return count;
        }

    }

Solution

  • Split the string into characters and store them into a Set. A Set keeps only unique elements. The elements of the Set will be the required characters and the size of the Set will give you the count of these characters.

    Do it as follows:

    import java.util.Arrays;
    import java.util.LinkedHashSet;
    import java.util.Set;
    import java.util.stream.Collectors;
    
    public class Testing {
        public static void main(String[] args) {
            String myString = "Hello my friends ";
            Set<String> set = Arrays.stream(myString.split("")).collect(Collectors.toCollection(LinkedHashSet::new));
            System.out.println("Unique characters including space: " + set);
            System.out.println("No. of unique characters including space: " + set.size());
        }
    }
    

    Output:

    Unique characters including space: [H, e, l, o,  , m, y, f, r, i, n, d, s]
    No. of unique characters including space: 13