Showing posts with label Character. Show all posts
Showing posts with label Character. Show all posts

Character Array to String in Java

 
We may seen lot of arrays like Integer, Character, Float and Double or even String array. In this tutorial we will see about converting Character array to String in Java code. We can achieve this by 2 ways like given below,
Character Array to String in Java


public class CharToString {

 public static void main(String[] args) {
  
  char[] myArray = new char[]{'j','a','v','a',' ','d','i','s','c','o','v','e','r'};
  
  //By 2 ways we can convert char[] to String and lets see both ways
  
  String type1 = String.valueOf(myArray);

String type2 = new String(myArray);
  
  
  System.out.println("TYPE 1 : "+type1);
  System.out.println("TYPE 2 : "+type2);
 }
}

OUTPUT:

TYPE 1 : java discover
TYPE 2 : java discover

Character Frequency in String

 
Character Frequency in String

This is one of the easy interview programming question under 3 years experience. Lets assume given a lengthy string and asked you to find each character frequency. For example the given string is "hello java discover". In this string 'h'=1 , 'o'=2 etc., need to find each character occurred counts need to printed. 
We can achieve this by many ways like converting to character array and then manipulating each character or in looping count each character occurrence and store in any Collection object etc., In our below example we will use HashMap to store characters as key and their counts in value part.


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CharFreq {

 public static void main(String[] args) {

  String str = "hello javadiscover";

  Map<Character, Integer> map = new HashMap<Character, Integer>();

  for (int i = 0; i < str.length(); i++) {
   char ch = str.charAt(i);
   if (map.get(ch) != null) {
    map.put(ch, (map.get(ch) + 1));
   } else {
    map.put(ch, 1);
   }
  }

  Set<Character> set = map.keySet();
  for (Character character : set) {
   System.out.println(character + " : " + map.get(character));
  }
 }
}


OUTPUT:


  : 1 // space character 
d : 1
e : 2
c : 1
a : 2
o : 2
l : 2
j : 1
h : 1
i : 1
v : 2
s : 1
r : 1