java - 从现有字符串获取新字符串的最佳方法

标签 java string

我需要重新排列字符串并获得一个新字符串。详情如下

Current String = 2014-10-15
New String = 20141015

我发现我们可以使用 split 或 sub string 来实现此目的。当我们考虑性能时最好的方法是什么

最佳答案

您可以使用Matcher.replaceAll方法。

Accroding to the String doc String.split() creates and compiles a new Pattern object. The same is true for the String.replace() methods. This compiling of a pattern each time can cause performance issues in your program if you call the split() or replace() functions in a tight loop.

下面是示例代码

Pattern replace = Pattern.compile("-");
Matcher matcher = replace.matcher("2014-10-15");
System.out.println(matcher.replaceAll(" "));//out put is:20141015

您可以多次使用此处创建的 Pattern 对象,因此它将节省与 Strring.replaceAll() 方法相关的时间。

阅读:Hidden evils of Java’s String.split() and replace()

关于java - 从现有字符串获取新字符串的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26380009/

相关文章:

java - 日期操作和 SQL 日期时间 WHERE 查询

c++ - 将 unicode 替换为 C++ 字符串中的空格时出现段错误

string - 如何在JavaCC中使用反斜杠转义字符换行?

java - 如何比较两种不同格式(时间戳和java.util.date)的sql查询中的时间?

java - 2 个 Servlet 之间的通信不适用于数据库

java - 生成无限并行流

java - 具有 @EmbeddedId 、 @GeneratedValue 和 @ManyToOne 的实体

java - java中如何查找字符串中的空格分隔字符?

c - 如何从C中的字符串中删除逗号

ruby-on-rails - 如何删除字符串末尾的所有 `/` 字符?