user3296744
user3296744

Reputation: 169

Improper output of the following String programs

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,

Upvotes: 1

Views: 70

Answers (3)

Nivas
Nivas

Reputation: 18334

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.

Upvotes: 0

fge
fge

Reputation: 121720

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500675

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

Upvotes: 2

Related Questions