So this is the task: Given a string, return a string where for every char in the original, there are two chars.
And I don't understand why its output are numbers instead of letters, I tried doesn't work?
public String doubleChar(String str) { String s = ""; for(int i=0; i<str.length(); i++){ s += str.charAt(i) + str.charAt(i); } return s; }
Expected :
doubleChar("The") → "TThhee"
doubleChar("AAbb") → "AAAAbbbb"
Output:
doubleChar("The") → "168208202"
doubleChar("AAbb") → "130130196196"
Java has a repeat function to build copies of a source string: String newString = "a". repeat(N); assertEquals(EXPECTED_STRING, newString);
Insert a character at the beginning of the String using the + operator. Insert a character at the end of the String using the + operator.
It happens because adding int and String gives you a new String. That means if you have int x = 5 , just define x + "" and you'll get your new String.
The + operator is overloaded in Java to perform String concatenation only for String
s, not char
s.
From the Java Spec:
If the type of either operand of a + operator is String, then the operation is string concatenation.
Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
In your case, char is converted to its primitive value (int), then added.
Instead, use StringBuilder.append(char)
to concatenate them into a String
.
If performance is not a concern, you could even do:
char c = 'A'; String s = "" + c + c;
and s += "" + c + c;
That will force the + String
concatenation operator because it starts with a String
(""). The Java Spec above explains with examples:
The + operator is syntactically left-associative, no matter whether it is determined by type analysis to represent string concatenation or numeric addition. In some cases care is required to get the desired result. For example [...]
1 + 2 + " fiddlers"
is"3 fiddlers"
but the result of:
"fiddlers " + 1 + 2
is"fiddlers 12"
In Java the char
primitive type is basically just a numeric value that maps to a character, so if you add two char
values together they produce a number and not another char
(and not a String
) so you end up with an int
as you're seeing.
To fix this you can use the Character.toString(char)
method like this:
s += Character.toString(str.charAt(i)) + Character.toString(str.charAt(i))
But this is all fairly inefficient because you're doing this in a loop and so string concatenation is producing a lot of String
objects needlessly. More efficient is to use a StringBuilder
and its append(char)
method like this:
StringBuilder sb = new StringBuilder(str.length() * 2); for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); sb.append(c).append(c); } return sb.toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With