如何重新分配StringBuffer的值?
我们如何重新分配 StringBuffer 或 StringBuilder 变量的值?
StringBuffer sb=new StringBuffer("teststr");
现在我必须将 sb 的值更改为“testString”而不清空内容。 我正在寻找一种可以直接执行此分配而无需使用单独的内存分配的方法。我认为我们只能在清空内容后才能执行此操作。
How can we re assign the value of a StringBuffer or StringBuilder Variable?
StringBuffer sb=new StringBuffer("teststr");
Now i have to change the value of sb to "testString" without emptying the contents.
I am looking at a method which can do this assignment directly without using separate memory allocation.I think we can do it only after emptying the contents.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
首先应该提到的是,
StringBuilder
通常优于StringBuffer
。来自StringBuffer
自己的 API :也就是说,我将坚持使用
StringBuffer
来获取答案的其余部分,因为这就是您所要求的;StringBuffer
所做的一切,StringBuilder
也...除了同步之外,这通常是不需要的。因此,除非您在多个线程中使用缓冲区,否则切换到 StringBuilder 是一项简单的任务。问题
所以您希望
sb
拥有String
值"testString"
在其缓冲区中?有很多方法可以做到这一点,我将列出其中一些来说明如何使用 API。最佳解决方案:执行从
"teststr"
到"testString"
的最小编辑。不可能比这更快了。这不必要地用
"tr"
覆盖"tr"
。这涉及由于
deleteCharAt
和insert
导致的转变。现在有点不同了:它并不神奇地知道它有需要编辑为
"testString"
的"teststr"
;它仅假设StringBuffer
在某处至少包含一次"str"
,并且需要将其替换为"String"
。现在假设您想要替换 所有 处出现的
"str"
并将其替换为"String"
。StringBuffer
没有内置此功能。您可以尝试以最有效的方式自己完成此操作,可以就地(可能使用 2 遍算法)或使用第二个StringBuffer
等。但我将使用
从
。在大多数情况下,这已经足够好了,而且绝对更清晰、更容易维护。它与输入字符串的长度呈线性关系,因此它是渐近最优的。字符串
替换(CharSequence, CharSequence)讨论
确切的内存位置不应该真正成为您关心的问题;事实上,
StringBuilder
和StringBuffer
都会在必要时将其内部缓冲区重新分配到不同的内存位置。防止这种情况的唯一方法是ensureCapacity
(或通过构造函数设置它),以便其内部缓冲区始终足够大,并且永远不需要重新分配。但是,即使
StringBuffer
偶尔重新分配其内部缓冲区,在大多数情况下也不会成为问题。大多数动态增长的数据结构(ArrayList
、HashMap
等)都以保留算法最优操作的方式实现,并利用成本摊销。我不会在这里进行摊销分析,但除非您正在做实时系统等,否则这对于大多数应用程序来说不应该是问题。显然,我不知道您的具体需求,但担心过早优化,因为您似乎担心大多数人永远不必担心的事情。
It should first be mentioned that
StringBuilder
is generally preferred toStringBuffer
. FromStringBuffer
's own API:That said, I will stick to
StringBuffer
for the rest of the answer because that's what you're asking; everything thatStringBuffer
does,StringBuilder
also... except synchronization, which is generally unneeded. So unless you're using the buffer in multiple threads, switching toStringBuilder
is a simple task.The question
So you want
sb
to have theString
value"testString"
in its buffer? There are many ways to do this, and I will list some of them to illustrate how to use the API.The optimal solution: it performs the minimum edit from
"teststr"
to"testString"
. It's impossible to do it any faster than this.This needlessly overwrites
"tr"
with"tr"
.This involves shifts due to
deleteCharAt
andinsert
.This is a bit different now: it doesn't magically know that it has
"teststr"
that it needs to edit to"testString"
; it assumes only that theStringBuffer
contains at least one occurrence of"str"
somewhere, and that it needs to be replaced by"String"
.Let's say now that you want to replace ALL occurrences of
"str"
and replace it with"String"
. AStringBuffer
doesn't have this functionality built-in. You can try to do it yourself in the most efficient way possible, either in-place (probably with a 2-pass algorithm) or using a secondStringBuffer
, etc.But instead I will use the
replace(CharSequence, CharSequence)
fromString
. This will be more than good enough in most cases, and is definitely a lot more clear and easier to maintain. It's linear in the length of the input string, so it's asymptotically optimal.Discussions
The exact memory location shouldn't really be a concern for you; in fact, both
StringBuilder
andStringBuffer
will reallocate its internal buffer to different memory locations whenever necessary. The only way to prevent that would be toensureCapacity
(or set it through the constructor) so that its internal buffer will always be big enough and it would never need to be reallocated.However, even if
StringBuffer
does reallocate its internal buffer once in a while, it should not be a problem in most cases. Most data structures that dynamically grows (ArrayList
,HashMap
, etc) do them in a way that preserves algorithmically optimal operations, taking advantage of cost amortization. I will not go through amortized analysis here, but unless you're doing real-time systems etc, this shouldn't be a problem for most applications.Obviously I'm not aware of the specifics of your need, but there is a fear of premature optimization since you seem to be worrying about things that most people have the luxury of never having to worry about.
“重新分配”是什么意思?您可以使用 < 清空内容code>setLength() 然后开始附加新内容(如果这就是您的意思)。
编辑:要更改部分内容,可以使用
replace()
。一般来说,这种问题可以通过查看相关类的 API 文档来轻松回答。
What do you mean with "reassign"? You can empty the contents by using
setLength()
and then start appending new content, if that's what you mean.Edit: For changing parts of the content, you can use
replace()
.Generally, this kind of question can be easily answered by looking at the API doc of the classes in question.
您可以使用
StringBuilder
代替StringBuffer
,如果可以的话,这通常是人们所做的事情(StringBuilder
不同步,因此它是更快但不是线程安全的)。如果您需要用另一个来初始化一个的内容,请使用 toString() 方法来获取字符串表示形式。要回收现有的StringBuilder
或StringBuffer
,只需调用setLength(0)
即可。编辑
您可以使用
replace()
函数覆盖一系列元素。要将整个值更改为newval
,您可以使用buffer.replace(0,buffer.length(),newval)
。另请参阅:You can use a
StringBuilder
in place of aStringBuffer
, which is typically what people do if they can (StringBuilder
isn't synchronized so it is faster but not threadsafe). If you need to initialize the contents of one with the other, use thetoString()
method to get the string representation. To recycle an existingStringBuilder
orStringBuffer
, simply callsetLength(0)
.Edit
You can overwrite a range of elements with the
replace()
function. To change the entire value tonewval
, you would usebuffer.replace(0,buffer.length(),newval)
. See also:您可能正在寻找 StringBuffer 的 Replace() 方法:
在内部,它会删除原始字符串,然后插入新字符串,但它可能会为您节省一个步骤:
使用 setLength(0) 将零长度的 StringBuffer 重新分配给变量,我想这不是你想要的:
You might be looking for the replace() method of the StringBuffer:
Internally, it removes the original string, then inserts the new string, but it may save you a step from this:
Using setLength(0) reassigns a zero length StringBuffer to the variable, which, I guess, is not what you want:
事实上,我认为
replace()
是最好的方法。我检查了Java源代码。它确实覆盖了旧字符。这是replace()的源代码:
Indeed, I think
replace()
is the best way. I checked the Java-Source code. It really overwrites the old characters.Here is the source code from replace():
更改 StringBuffer 的整个值:
这是更改 StringBuffer 的整个值的方法。
Changing entire value of StringBuffer:
This is how you can change the entire value of StringBuffer.
您可以与字符串进行转换,如下所示:
You can convert to/from a String, as follows: