更新Java String中替换方法的替代方法? [英] Faster alternatives to replace method in a Java String?

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

问题描述

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".

它有替换(和追加插入 delete ,等)你可以使用 toString 将其变形为真实的字符串

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

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

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