1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
//Using Hashmap package string_manipulation; import java.util.HashMap; public class CharCountInStringUsingHashMap { public static void main(String[] args) { //Creating a HashMap containing char as a key and occurrences as a value String inputString="My name is Snehal Dasharsth Jadhav"; HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>(); //Converting given string to char array char[] strArray = inputString.toCharArray(); //checking each char of strArray for (char c : strArray) { if(charCountMap.containsKey(c)) { //If char is present in charCountMap, incrementing it's count by 1 charCountMap.put(c, charCountMap.get(c)+1); } else { //If char is not present in charCountMap, //putting this char to charCountMap with 1 as it's value charCountMap.put(c, 1); } } //Printing the charCountMap System.out.println(charCountMap); } } //Using for loop package string_manipulation; public class charCountInString { public static void main(String[] args) { String s=new String("My name is snehal dasharath jadhav "); char []a=s.toCharArray(); for(int i=0;i<a.length;i++){ int count=1; for(int j=i+1;j<a.length;j++) { if(a[i]==a[j]) { count++; a[j]= '0'; } } if(count>1 && a[i]!='0'){ //System.out.println(a[i]); System.out.println("number of times repeated "+a[i]+" is "+count); } } }} |