如何从 CharBuffer 中获取字符串“hi”?toString()
似乎不起作用。
val a = CharBuffer.allocate(10);
a.put('h');
a.put('i');
val b = a.toString();
运行上述代码后的变量状态:
如何从 CharBuffer 中获取字符串“hi”?toString()
似乎不起作用。
val a = CharBuffer.allocate(10);
a.put('h');
a.put('i');
val b = a.toString();
运行上述代码后的变量状态:
CharBuffer
是相当低级的,实际上是用于 I/O 的东西,所以一开始它可能看起来不合逻辑。在您的示例中,它实际上返回了一个字符串,其中包含您未设置的剩余 8 个字节。要使其返回您的数据,您需要flip()
像这样调用:
val a = CharBuffer.allocate(10);
a.put('h');
a.put('i');
a.flip()
val b = a.toString();
您可以在Buffer的文档中找到更多信息
对于更典型的用例,它更容易使用StringBuilder
:
val a = StringBuilder()
a.append('h')
a.append('i')
val b = a.toString()
或者甚至使用包装的 Kotlin 实用程序StringBuilder
:
val b = buildString {
append('h')
append('i')
}