1
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,

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
user3296744
  • 169
  • 3
  • 9

3 Answers3

3

You essentially add:

char + int + String

Since + is left associative, you end up doing:

(char + int) + String

therefore int + String; and only at that step is the string concatenation happening.

A solution would be to use String.format():

String.format("%c%d,", str.charAt(i), count);
fge
  • 119,121
  • 33
  • 254
  • 329
2

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 :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Using the + operator on a a char and an int leads to a char representing the sum of the both (and does not concatenate). See this answer for a detailed explanation and exceptions.

So, the statement

finalString+=str.charAt(i)+count+",";

Ends up being char + int addition and not string concatenation.

To concatenate, convert the str.charAt(i)+ to String first.

Community
  • 1
  • 1
Nivas
  • 18,126
  • 4
  • 62
  • 76