在 Java 字符串中替换方法的更快替代方法? [英] Faster alternatives to replace method in a Java String?

查看:37
本文介绍了在 Java 字符串中替换方法的更快替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

replace 方法返回一个字符串对象而不是替换给定字符串的内容这一事实有点晦涩(但是当您知道字符串在 Java 中是不可变的时,这可以理解).通过在某些代码中使用深度嵌套的替换,我对性能造成了重大影响.有什么我可以用它代替它可以让它更快的吗?

The fact that the replace method returns a string object rather than replacing the contents of a given string is a little obtuse (but understandable when you know that strings are immutable in Java). I am taking a major performance hit by using a deeply nested replace in some code. Is there something I can replace it with that would make it faster?

推荐答案

这就是 StringBuilder 是为了.如果您要进行大量操作,请在 StringBuilder 上进行,然后在需要时将其转换为 String.

This is what StringBuilder is meant for. If you're going to be doing a lot of manipulation, do it on a StringBuilder, then turn that into a String whenever you need to.

StringBuilder 是这样描述的:

一个可变的字符序列.这个类提供了一个与 StringBuffer 兼容的 API,但不保证同步".

"A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization".

它有 replace(和 appendinsertdelete 等),你可以使用 toString 将其变形为真正的 String.

It has replace (and append, insert, delete, et al) and you can use toString to morph it into a real String.

这篇关于在 Java 字符串中替换方法的更快替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆