Count unique characters in a user-defined string

I need to write a program that takes into account the uniques characters in String specified by the user. For example, "abc" returns 3, and "aabbccd" returns 4. I cannot use advanced Java classes such as Map, Set, etc. I can only use arrays, strings, for loops, as well as loops if instructions. I am trying to use a nested loop, but I am confused about how to write an algorithm for the second loop.

public static int countUniqueCharacters(String input){ String orgInput = input.toLowerCase(); int count = 0; int stringLength = input.length(); for( int i = 0; i<stringLength; i++){ for(int j = 2; j > ji-1; j--){ char temp = orgInput.charAt(i); if (temp == orgInput.charAt(j)){ count++; 
+7
source share
11 answers

It is very simple :)

 public static int countUniqueCharacters(String input) { boolean[] isItThere = new boolean[Character.MAX_VALUE]; for (int i = 0; i < input.length(); i++) { isItThere[input.charAt(i)] = true; } int count = 0; for (int i = 0; i < isItThere.length; i++) { if (isItThere[i] == true){ count++; } } return count; } 

Example input "aab"

The first goes through the loop 3 times, each time in one char.

The value of "a" is 97, so it rotates if it [97] is true, then the second "a" is involved, which does the same thing, isItThere [97] is again set to true (therefore, it does not change anything).

After that, "b" is involved, the char value of "b" is 98, so isItThere [98] is set to true.

And then you have a second for loop, where you cyclically move the entire isItThere array. If you find any true statement, you increment the counter. In our case, you find isItThere [97] and isItThere [98] as a true operator, which means that you double and return 2.

+5
source

Using Java 8, you can do the following:

 public static long countUniqueCharacters(String input) { return input.chars() .distinct() .count(); } 

This creates an IntStream of char s, then takes only the values ​​of different values ​​and then counts the number of occurrences.

+36
source

Here's another solution:

 public static int countUniqueCharacters(String input) { String buffer = ""; for (int i = 0; i < input.length(); i++) { if (!buffer.contains(String.valueOf(input.charAt(i)))) { buffer += input.charAt(i); } } return buffer.length(); } 

The first pad of each character is stored in buffer . Therefore, you have all the characters one in buffer , therefore buffer.length() supplies the score you need.

+4
source

If you are stuck with Java 7, you can use an ArrayList and just add unique values ​​to it, and then return the size of the ArrayList, which should always work, even if the counter is zero.

  import java.util.ArrayList; public int getUniqeCount( String arg ) { ArrayList<Character> unique = new ArrayList<Character>(); for( int i = 0; i < arg.length(); i++) if( !unique.contains( arg.charAt( i ) ) ) unique.add( arg.charAt( i ) ); return unique.size(); } 
+4
source
 public static int countUniqueChars (String buf) { HashSet<Character> hash = new HashSet<>(); buf = buf.toUpperCase(); for (int i = 0; i < buf.length(); i++) hash.add(buf.charAt(i)); return hash.size(); } 
+2
source
 public static long calculateDistinctSubStringSum(String text) { Map<String, Integer> map = new HashMap<String, Integer>(); char[] charAarry = text.toCharArray(); for (int i = 0; i < charAarry.length; i++) { map.put(charAarry[i] + "", 1); } return map.size(); } 

This is what I did for the calculation, but I'm still looking for a quick way. If anyone knows, answer.

0
source

You can use HashSet collections to count unique items in a string. It allows only a unique element.

Code snippet

 public static int uniqueCount(String str) { HashSet<Character> al = new HashSet<Character>(); char[] arr= str.toCharArray(); for (int i=0; i<arr.length; i++) { al.add(arr[i]); } return al.size() ; } 

Follow this link to get the full code: ideone

0
source

Try to find out if the following code helps you:

 String myString = ""; for(int i=0; i< word.length(); i++) { if(myString.indexOf(word.charAt(i)) == -1) { System.out.println(word.charAt(i)); myString = myString + word.charAt(i); } } return myString.length(); 
0
source
 public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter String:"); int length = scanner.nextInt(); char[] ch1 = new char[length]; String[] input = new String[length]; for (int i = 0; i < length; i++) { String userInput = scanner.next(); input[i] = userInput; ch1= userInput.toCharArray(); Arrays.sort(ch1); System.out.println(ch1); } 
0
source

Unique characters in line:

This is the main topic of a Java interview where the interviewer wants to test knowledge of HashSet or indexOf (in the case of Java 7). Let's deal with the issue. Let's say the interview tells you
Check the uniqueness of the string: HashSet provides uniqueness. In other words, each object in a HashSet is represented only once. Therefore, we will use a HashSet.

 import java.util.HashSet; import java.util.Set; public class Abc { public static void main(String[] args) { String a = "Gini"; String aa = a.toLowerCase(); if( isUnique(aa) ) { System.out.println("All characters are unique"); }else { System.out.println("All characters are not unique"); } } public static boolean isUnique(String a ) { Set< Character> set = new HashSet<>(); char[] charArray =a.toCharArray(); for(Character ch :charArray) { if(!set.add(ch)) { return false; }//if }//foreach return true; } } 

The output in the case of GINI will be: All characters are not unique

Now the number of unique characters. Here we will also use HashSet because of its uniqueness.

 import java.util.HashSet; public class practice11 { public static void main(String[] args) { String a = "Gini"; String aa = a.toLowerCase(); System.out.println(countUniqueCharacters(aa)); } public static int countUniqueCharacters(String a) { char[] charArray = a.toCharArray(); HashSet<Character> set = new HashSet<Character>(); for(int i = 0 ; i< charArray.length ; i++) { set.add(charArray[i]); }//for return set.size() ;//This will give 3 } } 

The exit for Gini will be 3 (Gin will be considered).

The indexOf: indexOf () method returns the index of the first occurrence of a character, and then we compare it with -1.

 public class Abc { public static void main(String[] args) { String a = "Gini"; String aa = a.toLowerCase(); String t = " "; for (int i = 0; i < aa.length(); i++) { int pp = aa.charAt(i) ; if(t.indexOf(aa.charAt(i)) == -1 ) { t = t + aa.charAt(i); }//if }//for System.out.println(t );// This will give => gin System.out.println(t.length()); // this will give 3 }//main }//end 

In Java 8, this is extremely simple. We just need to use chars (). Different (). Count (). But the type of return will be long.

 class Abc{ public static void main(String[] args) { String a = "Gini"; String aa = a.toLowerCase(); System.out.println( countUnique(aa)); } private static long countUnique(String aa) { // this will give 3(gin. another i will be not be counted as we have used distinct()) return aa.chars().distinct().count() ; } } 

Another classic interview question: find the first non-repeating character in the string OR the first unique character in the string. This problem can be solved using HashMap knowledge.

 class Abc{ public static void main(String[] args) { String a = "GinaRani" ; // Output will be G System.out.println( firstNonRepeatingCharacter(a) ); }//main public static Character firstNonRepeatingCharacter(String a){ Map<Character, Integer> map = new HashMap<>(); char[] charArray = a.toCharArray(); for( Character ch : charArray){ if( map.containsKey(ch) ) { map.put(ch, map.get(ch) +1 ) ; } else{ map.put(ch, 1); } }//for // 1st non repeating character for( int i = 0 ; i < a.length(); i ++ ){ char chh = a.charAt(i); if( map.get(chh) == 1 ){ System.out.println("first non repeating character in the String is : "); return chh ; }//if }//for return null; }//firstNonRepeatingCharacter }//end 

We will do this with a list comprehension in Python. We do not use the set () operator. In Python:

 string = 'GiniGinaProtijayi' unique = [] [ unique.append(ch) for ch in string if ch not in unique ] lengthofUniqueCharacters = len(unique) print("length of Unique Characters => " ,lengthofUniqueCharacters) print("as a list => ",unique) print("as a string => " , ''.join(unique)) 

Just to print single characters in Java 8:

 public class Test5 { public static void main(String[] args) { String a = "GinaGini"; String aa = a.chars().distinct() .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); System.out.println(aa);//Gina }// main } 
0
source

If you are allowed to use Java suites, the following code is readable, compact, and does the job smoothly

 public static int countUniqueChar(String word){ Set<Character> wordSet = new HashSet<>(); for(Character c : word.toCharArray()) wordSet.add(c); return wordSet.size(); } 
0
source

All Articles