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,

1
  • 3
    char + int => int! Commented Apr 1, 2014 at 12:28

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.