Sorting frequency of chars - java

I just made an algorithm that counts the frequency of chars in a String. What I am confused about is how to sort the frequency so the character with the greatest number of occurences is listed at the top, and the least at the bottom.
At first I tried having another variable 'fc' (for frequency counter) to coincide with my original counter variable 'k'. However I am stuck in the thought process of how to go about sorting this frequency, the fc var I made is just useless.
Thanks for any help provided!
Here is my code:
import java.io.*;
public class Freq
{
public static void main(String args[])throws IOException
{
//read input stream
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int ci,i,j,k,l,fc;l=0;
String str,str1;
char c,ch;
System.out.println("Enter your String");
str=in.readLine();
i=str.length();
//cycle through ASCII table chars and obtain chars typed
for(c='A';c<='z';c++)
{
k=0;
fc=0; //fc keeps count like k
for(j=0;j<i;j++)
{
ch=str.charAt(j);
if(ch==c)
k++;
fc=k-1; //was going to represent this counter for 'less than k'
}
if(k>0)
System.out.println("The character "+c+" has occured for "+k+" times");
}
}
}

You will need to store them all first. You can use a HashMap to store them all, it will also simplify your counting routine. Then Collections.sort on the entry set. You will need to make a Comparable> to compare the entry values for sorting.
Edited to add sample code....
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your String");
String line = in.readLine();
HashMap<Character,Integer> counts = new HashMap<>();
for(char c : line.toCharArray()) {
Integer count = counts.get(c);
if (count == null) {
count = 0;
}
counts.put(c, ++count);
}
List<Entry<Character,Integer>> list = new ArrayList<>(counts.entrySet());
Collections.sort(list, new Comparator<Entry<Character,Integer>>() {
#Override
public int compare(Entry<Character, Integer> o1,
Entry<Character, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
for(Entry<Character,Integer> entry : list) {
System.out.println("The character "+entry.getKey() +" has occured for "+ entry.getValue()+" times");
}

You can follow these steps:
1) Create a class call CharCount having two fields : char and freq. Override equals to return true if characters are equal and override hashcode to return character's hashcode. Make it implement Comparable and override compare and return -1,0 or 1 based on values of freq of objects being compared
2) Have a Set of CharCount
3)Each time you find a character create an instance of this class with character and freq as 0.
4)Check if it exists in set and update feq accordingly
5) Sort set data yourself or call Collections.sort

I would do it like this:
int[] frequencyArray = new int['z' -'A'];
String inputString = "ttttttttttttttttest";
for(int i = 0; i<inputString.length();i++)
{
frequencyArray[inputString.charAt(i) -'A']++;
}
Then, you can sort this array by any of the popular sorting algorithms of your choosing.
EDIT Made the code more memory efficient.

Make a function count that gives you the count of particular character and sort on behalf of count, e.g
if( count(str,str.charAt[j]) > count(str,str.charAt[j+1]) )
SWAP
its better to convert str to char array before this, then it will be like
count(chararr,charrarr[j])

This one works faster than Hashmap solution:
public static void frequencySort(String s) {
int[] f = new int[256];
for (int c : s.toCharArray())
f[c]++;
List<CharStore> list = new ArrayList<>();
for (int i = 0; i < f.length; i++) {
if (f[i] != 0) list.add(new CharStore(i, f[i]));
}
Collections.sort(list);
for (CharStore c : list) {
System.out.println(((char)c.c) + " has occured " + c.count + " times";
}
}
static class CharStore implements Comparable<CharStore> {
int c;
int count;
public CharStore(int c, int count) {
this.c = c;
this.count = count;
}
#Override
public int compareTo(CharStore o) {
return o.count - count;
}
}

Related

Find the occurrence of each character in a given string

"I want to find and print the occurrence of each character of given string and i have build my own logic but there is some problem.for example if i gave input as 'JAVA'.
the output that my program produce will be
J 1
A 2
V 1
A 1
Expected output :
J 1
A 2
V 1
i doesn't want to print A again. I hope you all get it what is the problem in my code."
import java.util.Scanner;
public class FindOccuranceOfCharacter {
public static void main(String[] args) {
// TODO Auto-generated method stub
String x;
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
x = input.nextLine();
x = x.toUpperCase();
int size = x.length();
for(int i =0;i<size;i++) {
int count=1;
char find = x.charAt(i);
for(int j=i+1;j<size;j++) {
if(find == x.charAt(j)) {
count++;
}
}
System.out.printf("%c\t%d",x.charAt(i),count);
System.out.println();
}
}
}
The reason your code prints the way it does is that your loop prints each character (and subsequent matches) for a given index. You really need to store the character and counts in a data structure with one loop, and then display the counts with a second. A LinkedHashMap<Character, Integer> is perfect for your use case (because it preserves key insertion order, no additional logic is needed to restore input order). Additional changes I would make include using String.toCharArray() and a for-each loop. Like,
Map<Character, Integer> map = new LinkedHashMap<>();
for (char ch : x.toUpperCase().toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (char ch : map.keySet()) {
System.out.printf("%c\t%d%n", ch, map.get(ch));
}
Which I tested with x equal to JAVA and got (as requested)
J 1
A 2
V 1
Using hashMap it's easy to accumulate the number of occurrences and you can easily print iterating the HashMap.
This is the code:
public class FindOccuranceOfCharacter {
public static void main(String[] args) {
String x;
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
x = input.nextLine();
HashMap<Character,Integer> occurance = new HashMap<Character,Integer>();
x = x.toUpperCase();
int size = x.length();
for(int i =0;i<size;i++) {
int count=1;
char find = x.charAt(i);
occurance.put(find, occurance.getOrDefault(find, 0) + 1);
}
for (Character key : occurance.keySet()) {
Integer value = occurance.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
}
This is not an optimal solution, but I have tried to change your code as little as possible:
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
// use a StringBuilder to delete chars later on
StringBuilder x = new StringBuilder(input.nextLine().toUpperCase());
for(int i=0;i<x.length();i++) {
int count=1;
char find = x.charAt(i);
// go through the rest of the string from the end so we do not mess up with the index
for(int j=x.length()-1;j>i;j--) {
if(find == x.charAt(j)) {
count++;
// delete counted occurences of the same char
x.deleteCharAt(j);
}
}
System.out.printf("%c\t%d",x.charAt(i),count);
System.out.println();
}
}
My more preferred Java stream would look like this:
input.nextLine().toUpperCase().chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + "\t" + v));

To print the first biggest and second biggest elements in a string

Below is the code I have implemented. My doubt here is: when I am trying to print the first biggest and second Biggest values in the string, the output I get is in the order of [second biggest, first biggest].
Here is the output of what I got for the below code:
The output of the map is: real--6
The output of the map is: to--2
The output of the map is: world--1
The output of the map is: hello--0
The list after insertion is: [to, real]
The list inserted as [biggest,secondBiggest] after calling main is: [to, real]
......
but, I want The list after insertion to be: [real, to].
public class ReadString {
static String input = "This is a real project with real code to do real things to solve real problems in real world real";
public static void main(String[] args) {
List<String> lst = ReadString.RepeatedString("This is a real project with real "
+ "code to do real things to solve real " + "problems in real world real");
System.out.println("The list inserted as [biggest,secondBiggest] after calling main is: " + lst);
}
public static List<String> RepeatedString(String s) {
String[] s2 = input.split(" ");
String[] key = { "real", "to", "world", "hello" };
int count = 0;
Integer biggest = 0;
Integer secondBiggest = 1;
Map<String, Integer> map = new HashMap<String, Integer>();
for (int j = 0; j < key.length; j++) {
count = 0;
for (int i = 0; i < s2.length; i++) {
if (s2[i].equals(key[j])) {
count++;
}
}
map.put(key[j], count);
System.out.println("The output of the map is: " +key[j] + "--" + count);
}
/*
* To find the top two most repeated values.
*/
List<Integer> values = new ArrayList<Integer>(map.values());
Collections.sort(values);
for (int n : map.values()) {
if (biggest < n) {
secondBiggest = biggest;
biggest = n;
} else if (secondBiggest < n)
secondBiggest = n;
}
/* To get the top most repeated strings. */
List<String> list = new ArrayList<String>();
for (String s1 : map.keySet()) {
if (map.get(s1).equals(biggest))
list.add(s1);
else if (map.get(s1).equals(secondBiggest))
list.add(s1);
}
System.out.println("The list after insertion is: " +list);
return list;
}
}
The problem appears to be when you are adding items to the list. As you are iterating through the map.keySet(), there is no guarantee that you will get the biggest item first. The smallest change I would make would be to add the biggest item first in the list.
for (String s1 : map.keySet()) {
if (map.get(s1).equals(biggest))
list.add(0, s1);
else if (map.get(s1).equals(secondBiggest))
list.add(s1);
}
This way, if secondBiggest is added first, biggest will be at the top of the list.
We can simplify your approach quite a bit if we extract the word and count into a simple POJO. Something like,
static class WordCount implements Comparable<WordCount> {
String word;
int count;
WordCount(String word, int count) {
this.word = word;
this.count = count;
}
#Override
public int compareTo(WordCount o) {
return Integer.compare(count, o.count);
}
}
Then we can use that in repeatedString. First, count the words in the String; then build a List of WordCount(s). Sort it (since it's Comparable it has natural ordering). Then build the List to return by iterating the sorted List of WordCount(s) in reverse (for two items). Like,
static List<String> repeatedString(String s) {
Map<String, Integer> map = new HashMap<>();
for (String word : s.split("\\s+")) {
map.put(word, !map.containsKey(word) ? 1 : 1 + map.get(word));
}
List<WordCount> al = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
al.add(new WordCount(entry.getKey(), entry.getValue()));
}
Collections.sort(al);
List<String> ret = new ArrayList<>();
for (int i = al.size() - 1; i >= al.size() - 2; i--) {
ret.add(al.get(i).word);
}
return ret;
}
Finally, your main method should use your static input (or static input should be removed)
static String input = "This is a real project with real code to do "
+ "real things to solve real problems in real world real";
public static void main(String[] args) {
List<String> lst = repeatedString(input);
System.out.println("The list inserted as [biggest,"
+ "secondBiggest] after calling main is: " + lst);
}
And I get (as requested)
The list inserted as [biggest,secondBiggest] after calling main is: [real, to]
If you are only concerned about biggest and secondbiggest,
you can refer to the code below.
Instead of creating the list directly, I created an array, added required elements on specified positions. (This way it becomes more readable)
and finally convert the array to a list.
/* To get the top most repeated strings. */
String[] resultArray = new String[2];
for (String s1 : map.keySet()) {
if (map.get(s1).equals(biggest))
resultArray[0]=s1;
else if (map.get(s1).equals(secondBiggest))
resultArray[1]=s1;
}
List<String> list = Arrays.asList(resultArray);

How can I check character occurrence in a string?

My Question is-
Input is string. Return true if the String has exactly 1 character that appears twice in the string, 0 character that appear thrice in the string, and at least 1 character that appear four or more times in the string. There is a problem in my code and I am unable to find out the problem.
public class CheckCharacterOccurence {
static String testcase1 = "jjiiiiyy";
public static void main(String[] args) {
CheckCharacterOccurence testInstance = new CheckCharacterOccurence();
boolean result = testInstance.checkCharacterOccurence(testcase1);
System.out.println(result);
}
public boolean checkCharacterOccurence(String str) {
char ch=' ';
char ch1=' ';
int temp=0;
int temp1=0;
int temp2=0;
int count=0;
for(int i=0;i<str.length();i++){
ch=str.charAt(i);
for(int j=i;j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
ch1=str.charAt(i);
count++;
}
}
System.out.println(count);
if(count==2&&ch!=ch1){
temp++;
}
if(count==3&&ch!=ch1){
temp1++;
}
if(count>=4){
temp2++;
}
count=0;
}
if(temp==1&&temp1==0&&temp2>=1){
return true;
}
return false;
}
}
I would suggest using a map
For all characters in string, increment map[that_char]
At last iterate over map to find how many times each character appeared.
Alternatively you can use array also to keep count.
Something like
int [] ctr = new int[256]
ctr = all zeroes
for (ch : string)
ctr[ch]++
mxocc = 0
maxch = 'a'
for(ch = a, b, c, d, e...)
if(ctr[ch] > maxocc) maxocc = ctr[ch] and maxch = ch
Output require info
hey you can figure out the problem ... atleast i can give to some extend same code , you can check it and try to solve your problem... This program finds the pattern in the string, now you can go through this program, and try to solve ur problem in your program by your own self.and try to do it by your own then only ur coding skills will get improved.and vote this answer if u fing it really helpful
#include<stdio.h>
#include<string.h>
int occur(char[],char[]);
int occur(char sent[],char pattern[])
{
int count=0;
for(int i=0,j=i;sent[i]!='\0';)
{
if(sent[i+j]==pattern[j]&&pattern[j]!='\0')
{
j++;
}
else if(j==strlen(pattern))
{
count++;
i=i+j;
j=0;
}
else
{
i++;
j=0;
}
}
return count;
}
int main()
{
char sent[] = "aabaabaaabbbabababddfggaabbbasab";
char pattern[] = "aba";
int result = occur(sent,pattern);
printf("\nNo of Occurrences --- > %d",result);
return 0;
}
You should simplify your code. For example there is not need to use those complex for-loops, you can use a for-each.
This code finds out the frequency of characters in a string and stores it in a Map.
import java.util.*;
public class CheckCharacterOccurence {
public static void main(String[] args) {
Map<Character, Integer> counting = new HashMap<Character, Integer>();
String testcase1 = "Helloooo";
for(char ch: testcase1.toCharArray()){
Integer freq = counting.get(ch);
counting.put(ch, (freq == null) ? 1 : freq + 1);
}
System.out.println(counting.size() + " distinct characters:");
System.out.println(counting);
}
}

How to find the number of different duplicate values in an array with Java

I have a slight problem with a programme im working on, I need to be able to look through an array in Java and find the number of different duplicates in that array, for example if the array have the values 4, 6, 4 I need to be able to display:
There are:
2 words of length 1 (4 characters)
1 word of length 2 (6 characters)
What I've currently got is -
public class wordLength {
public static void main(String[] args) {
String userInput1 = "Owen Bishop Java ";
String [] inputArray = userInput1.split(" ");
for (int i = 0; i < inputArray.length; i++) {
int length = inputArray[i].length();
int inputArray2 = length;
System.out.println(inputArray2);
}
}
}
This currently will split the string into an array whenever there is a space, and then find and print the length of each of the words in the array, I need to show the amount of words that are the same length.
I'm really new to Java and appreciate this is probably an incredibly easy problem but any help would be hugely appreciated, thanks.
Without writing the whole thing (or making use of 3rd party libraries - I note you're new to Java so let's not complicate things), I would consider the following.
Make use of a Map<Integer,Integer> which would store the number of words of a particular length. e.g. to populate:
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (String word : words) {
Integer current = counts.get(word.length());
if (current == null) {
current = 0;
}
current++;
counts.put(word.length(), current);
}
and then iterate through that to output the number of words per word count. Note that the above makes use of boxing.
The advantage of using a Map is that (unlike your array) you don't need to worry about empty counts (e.g. you won't have an entry if you have no words of length 5). That may/may not be an issue depending on your use case.
You can create an int array of length 20(or the maximum word length in English) and increase the index value before you print that value.
arr[length]++;
public class wordLength {
public static void main(String[] args) {
String userInput1 = "Owen Bishop Java ";
String [] inputArray = userInput1.split(" ");
Map<Integer,Integer> wordLengths = new HashMap<Integer,Integer>();
for (int i = 0; i < inputArray.length; i++) {
int length = inputArray[i].length();
if (wordLengths.containsKey(length))
wordLengths.put(length, wordLengths.get(length) + 1);
else
wordLengths.put(length, 1);
}
for (Integer length : new TreeSet<Integer>(wordLengths.keySet()))
System.out.println("Length: " + length + " Count: " + wordLengths.get(length));
}
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class wordLength {
public static void main(String[] args) {
String userInput1 = "Owen Bishop Java ";
String [] inputArray = userInput1.split(" ");
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < inputArray.length; i++) {
int length = inputArray[i].length();
if(map.get(length)==null){
map.put(length, 1);
}
else map.put(length, map.get(length)+1);
}
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println("words of length " +pairs.getKey() + " are " + pairs.getValue());
}
}
}
The output will be:
words of length 4 are 2
words of length 6 are 1
The beginning of your code looks good. What you basically want to keep track of (in my understanding) is a mapping from String length to the number of times this occurred.
public class wordLength {
public static void main(String[] args) {
String userInput1 = "Owen Bishop Java ";
String [] inputArray = userInput1.split(" ");
Map<Integer, Integer> counter = new HashMap<>(); //please note that I use the 'diamond' notation here, this is for Java 1.7 and higher.
for (int i = 0; i < inputArray.length; i++) {
int length = inputArray[i].length();
Integer num = counter.get(length);
if (num == null) {
num = 1;
}
else {
num++;
}
counter.put(length, num);
//or counter.put(length, num == null ? 1 : num++); instead of the if-else
}
//print the results
for (Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("There are " + entry.getValue() + " words with length " + entry.getKey() + ".");
}
}
}
The previous submitted method of arr[length]++; does work, but uses way to many space. Say you have only words of length 20 and beyond, then the first 20 elements of this arr are useless...
Please also note that you can use the map.entrySet() method from the Map interface. It is a better coding practice to use this method than using map.keySet() and after that looking up the associated value. This saves you much look up time. (especially with large user inputs!!!)
I have 2 solutions for above problem
Using extra space i.e. Map to store unique value. Complexity O(n) + Space(N) [N= #unique value]
No extra space. Sorts the input and counts values. Complexity nLog(n) + n
First Solution
Create a map to store each unique value as key and its count as value
Iterate over input array
If value exists as key then increment counter
ELSE if value does exist in map, then put value and set counter as 1
private static void UniqueValueUsingMap(int[] a){
//Map with
// key: unique values
// Value: count as each value (key)
Map<Integer, Integer> store = new HashMap<Integer, Integer>();
for (int i : a) {
Integer key = Integer.valueOf(i);
Integer count = null;
if(store.containsKey(key)){
count = store.get(key);
}else{
count = 0;
}
count++;
store.put(key, count);
}
}
Second solution
Sort the given Array nlog(n). All same values will be together after sort.
Iterate over sorted array
Maintain 2 variable i.e. previous value and counter for current value
When value change, print the value/count and reset the counter
Note: : int defaults to 0 inital value. Need to add additional check for it.
private static void CountValueUsingSort(int[] a){
//Sort the input array
Arrays.sort(a);
int currentValue = 0;
int counter =0;
for (int curr : a) {
if(curr != currentValue){
System.out.println("Value: " + currentValue + " Count:" + counter);
//Reset counter
counter = 0;
}
currentValue = curr;
//increment Count
counter++;
}
}

Occurrences of each letter

this is the program that I have to write but I get this error,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
50
Write a complete program using two arrays, upper and lower to keep the upper
And lower alphabet respectively.
Ask the user to enter string example:
This is a test from Jupiter. Soon you will see who is from
Jupiter!!! May be Dr. D.
Your program should parse the string and keep track of number of alphabet. Both arrays are indexed from 0 to 25. The logical way to do this is to use upper[0] to
Count the number of ‘A’, and upper[1] to count number of ‘B’ and so on. Likewise
For the lower array.
Output should look like:
A: 0 a:2
B: 0 b:0
.
.
.
Z:0 z:0
Code
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Letter {
public static void main(String[] args) {
// this is get results
char[] chars = userEnters();
System.out.println();
System.out.println("Occurrences of each letter are:");
PrintArray(countLow(chars), countUp(chars));
}
public static char[] userEnters() {
String inputX = JOptionPane.showInputDialog("Enter line of text: ");
char[] chars = inputX.toCharArray();
return chars;
}
public static int[] countLow(char[] input) {
int[] counts = new int[26];
for (int i = 0; i < input.length; i++) {
counts[input[i] - 'a']++;
}
return counts;
}
public static int[] countUp(char[] input2) {
int[] countsUp = new int[26];
for (int i = 0; i < input2.length; i++) {
countsUp[input2[i] - 'A']++;
}
return countsUp;
}
public static void PrintArray(int[] counts, int[] countsUp) {
for (int i = 0; i < counts.length; i++) {
System.out.print(counts[i] + " " + (char) ('a' + i) + " ");
System.out.print(countsUp[i] + " " + (char) ('A' + i) + "\n");
}
}
}
If you enter a character that is not a large cap, countUp will throw an exception and if you enter a character that is not a small cap, countLow will throw an exception.
Example: if you call countLow on a A, you calculate 'A' - 'a' which returns -32 and a negative index is not allowed.
You need to review your logic and call either countLow or countUp depending on the case of the letter and filter invalid characters out.
Or refactor the whole thing and use a char[52] for example where you hold both small and large caps.
I Hope you don't mind I did refactor your code a bit.
Please have a look at this alterantive solution to your problem and then read the comments at the bottom of the answer.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JOptionPane;
public class LetterCounter {
//Hash maps don't allow duplication.
//The letter will be the Key and the repetitions the value(Your goal!)
private Map<Character, Integer> resultsMap = new HashMap<Character, Integer>();
public static void main(String[] args) {
LetterCounter letterCounter = new LetterCounter();
letterCounter.fillMap();
letterCounter.showMapContents();
}
private void showMapContents() {
for (Entry<Character, Integer> entry : resultsMap.entrySet())
{
System.out.println("'" + entry.getKey() + "' - " + entry.getValue() + " times");
}
}
private void fillMap() {
char[] userInputAsArray = getUserInputAsLetterArray();
for (int currentLetter = 0; currentLetter < userInputAsArray.length; currentLetter++) {
int count = getOccurences(userInputAsArray[currentLetter],userInputAsArray);
resultsMap.put(userInputAsArray[currentLetter], count);
}
}
private int getOccurences(int letter, char[] userInputAsArray) {
int counter = 0;
for (int currentIndex = 0; currentIndex < userInputAsArray.length; currentIndex++) {
if(userInputAsArray[currentIndex] == letter)
counter++;
}
return counter;
}
public char[] getUserInputAsLetterArray() {
String userInput = JOptionPane.showInputDialog("Enter line of text: ");
char[] chars = userInput.toCharArray();
return chars;
}
}
Whenever you want to do an exercise where you need to manipulate data, you should pick the best data structure for the job. In your case, I think the hash map could be interesting because it avoids duplicates and will do a big part of the job for you. Find a very good cheat sheet in this link: http://www.janeve.me/articles/which-java-collection-to-use
I noticed that you used a lot static and that is not a very Object Oriented thing to do. As an alternative, when you want to just on the run do some quick examples like this one, you can just initialize the class inside itself.
I hope this was useful.
You should probably consider moving from arrays to a more complex and powerful data structure like Map<Character,Integer>.
With that data structure the code you need would look something like
public Map<Character,Integer> countOccurrencies(String inputString){
Map<Character,Integer> occurrencies = new HashMap<Character,Integer>();
for(Character c : inputString){
if(occurrencies.containsKey(c)){
occurrencies.put(c, occurrencies.containsKey(c) + 1);
} else {
occurrencies.put(c, 1);
}
}
return occurrencies;
}
Answer in java:
Here, countOfOccurances("pppggggkkkkpgaaaa") gives you count of occurrences of each character from a String
public static void countOfOccurances(String mainStr)
{
String temp = "";
for (int i = 0 ; i < mainStr.length();i++)
{
CharSequence ch = String.valueOf(mainStr.charAt(i));
temp=mainStr.replace(ch, "");
int count = (mainStr.length()-temp.length());
System.out.println(ch+" = "+count);
mainStr = temp;
i = -1;
}
}
Output of method:
p = 4
g = 5
k = 4
a = 4

Categories

Resources