public class NoOfConsAlphabet {
public static void main(String[] args) {
String str="aaabbddaabbcc";
int count=1;
String finalString="";
for(int i=1;i<str.length()-1;i++)
{
if(str.charAt(i)==str.charAt(i+1))
{
++count;
}
else
{
finalString+=str.charAt(i)+count+",";
count=1;
}
}
System.out.println(finalString);
}
}
I am getting this as my o/p:99,100,102,99,100, Can someone tell me how to get this resolved not sure what this is?Need to get an output of a3,b2,d2,a2,b2,
This is the problem:
str.charAt(i)+count+","
That's performing a char
+ int
conversion, which is just integer arithmetic, because +
is left-associative. The resulting integer is then converted to a string when ","
is concatenated with it.
So this:
finalString+=str.charAt(i)+count+",";
is equivalent to:
int tmp1 = str.charAt(i)+count;
String tmp2 = tmp1 + ",";
finalString += tmp2;
I suggest you use:
String.valueOf(str.charAt(i)) + count
to force string concatenation. Better yet, use a StringBuilder
:
builder.append(str.charAt(i)).append(count).append(",");
That's clearer and more efficient :)
See more on this question at Stackoverflow