I'm new to Java. I'm trying to print the characters present in the string along with their count. The count only increments when the same character is present next to it.
Ex:
I/O : Sssgs
O/P : S1s2g1s1
Counting the occurence of each character gives the count of the full count regardless of the characters not being present next to each other. Tampering with the i & j loops gives an OutOfBounds error.
//ch[] is the String converted to a character array.
//count[] is an array to store count of the characters
//Checks if present char and next char are same and increments count
for(int i=0;i<ch.length;i++)
{
count[i]=0;
for(int j=0;j<ch.length;j++)
{
if(ch[i]==ch[j])
{
count[i]++;
}
}
}
//Prints Distinct char
for(int i=0;i<ch.length;i++)
{
int j;
for(j=0;j<i;j++)
{
if(ch[i]==ch[j])
{
break;
}
}
if(i==j)
{
System.out.print(ch[i]+" "+count[i]);
}
}
The Input is > HelloWorld
The expected output should be > H1 e1 l2 o1 W1 o1 r1 l1 d1