Jared Massa - 10 days ago 6
Java Question

# Frequency counter for Strings in Java

I have a

`string`
that a user will type in representing time. i.e "10:05"

I've been searching for a while, and cannot find a way to search this
`string`
to find a specific number. The reason I need this number, is because I need to take each number and use an
`algorithm`
to discover how much power it takes to display this number on a digital clock. To do so, I need the frequency of each number. For example, if the time was 10:05, the number 0 would occur 2 times, and I can take that 2 and multiply it by the necessary numbers to discover the power needed.

This worked for me: (Assuming that time is entered always in xx:yy format)

`````` public static void main(String args[])
{
String time = "10:07"; //User Input
time = time.replace(":", "");
char digit[] = {time.charAt(0), time.charAt(1), time.charAt(2), time.charAt(3)};
int[] count = new int[digit.length];
Arrays.sort(digit);

for (int i = 0; i < digit.length; i++)
{
count[i]++;
if (i + 1 < digit.length)
{
if (digit[i] == digit[i + 1])
{
count[i]++;
i++;
}
}
}

for (int i = 0; i < digit.length; i++)
{
if (count[i] > 0)
{
System.out.println(digit[i] + " appears " + count[i]+" time(s)");
}
}
}
``````

Output:

``````0 appears 2 time(s)
1 appears 1 time(s)
7 appears 1 time(s)
``````
Source (Stackoverflow)