0

How to get the string "hi" from the CharBuffer? toString() does not seem to work.

val a = CharBuffer.allocate(10);
a.put('h');
a.put('i');
val b = a.toString();

Variable states after running the code above:

enter image description here enter image description here

enter image description here

Damn Vegetables
  • 11,484
  • 13
  • 80
  • 135

1 Answers1

1

CharBuffer is pretty low-level and really meant for I/O stuff, so it may seem illogical at first. In your example it actually returned a string containing remaining 8 bytes that you didn't set. To make it return your data you need to invoke flip() like this:

val a = CharBuffer.allocate(10);
a.put('h');
a.put('i');
a.flip()
val b = a.toString();

You can find more in the docs of the Buffer

For more typical use cases it is much easier to use StringBuilder:

val a = StringBuilder()
a.append('h')
a.append('i')
val b = a.toString()

Or even use a Kotlin util that wraps StringBuilder:

val b = buildString {
    append('h')
    append('i')
}
broot
  • 21,588
  • 3
  • 30
  • 35