Stringbuilder在java中进行字符串转换 [英] Stringbuilder to string conversion in java
本文介绍了Stringbuilder在java中进行字符串转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我们可以使用toString()和new String(stringbuilder)函数和构造函数将字符串构建器转换为字符串。但是我想知道为什么这个语句引发错误的原因是StringBuilder无法转换为String
I know we can convert a string builder to string using toString() and new String(stringbuilder) functions and constructor.. But I want to know the reason why this statement raises an error as "StringBuilder cannot be converted to String"
String s = (String) StringBuilder;
我尝试过:
将stringbuilder转换为字符串使用string literal
What I have tried:
Convert stringbuilder to string using string literal
推荐答案
因为StringBuilder
是一个不同的类,不能直接用作字符串
。您必须使用toString()
方法,如文档中所述。
Because aStringBuilder
is a different class, and cannot be directly used as aString
. You must use thetoString()
method, as described in the documentation.
没有<$ c $之类的东西c> StringBuilder 到字符串
转换。
StringBuilder
class为您提供toString
方法,该方法允许您获取实际存储在StringBuilder
的内部缓冲区中的字符串对象。
你必须使用
There is no such thing as aStringBuilder
toString
conversion.
StringBuilder
class provides you with atoString
method which allows you to get the string which is actually stored in the internal buffer of theStringBuilder
object.
You have to use
String s = sb.ToString();
, sb
是 StringBuilder
类的变量。
, sb
being a variable of the StringBuilder
class.
// Bad code!
String s = (String)StringBuilder;
是至少在两个级别上不正确:
- 你不能施放
StringBuilder
变量到stri直接。
-
StringBuilder
是一个类,而不是一个变量。你不能把类投射到任何东西上,你只能投射变量。
- You cannot cast a
StringBuilder
variable to a string directly.
StringBuilder
is a class, not a variable. You cannot cast a class to anything, you only cast variables.
is not correct on at least two levels:
嗯,我想在类型转换你的情况下我必须检查IS-A测试,在这种情况下会失败,因为StringBuilder不是String。在转换的情况下,你明确地必须使用toString()(注意't'不是大写)。
Well, I guess in case of type casting you'll have to take check for the "IS-A" test which would fail in this case as StringBuilder is NOT a String. In case of conversion you explicitly have to use the "toString()"(note that 't' isn't capital).
这篇关于Stringbuilder在java中进行字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文