繁体   English   中英

Java-从数组替换字符串的最快方法是什么

[英]Java - what is the fastest method to replace string from array

我有三个字符串元素的数组,0,1,2。 我有绳子

this is $0 string some text here $1 another text here $2 and some here

将$ 0替换为array [0],将$ 1替换为array [1]和将$ 2替换为array [2]的最快方法是什么。 我需要最快的,因为我确实有很多这样的操作。

编辑:

目前,我使用以下方法:

Formatter formatter=new Formatter();
String[] array=new String[]{"aaa","bbb","ccc"};
String result=formatter.format("some text %s another tett %s more text %s",array));

使用StringBuffer并假设您的标记是“排序的”(即$ 0,$ 1,$ 2,并且标记不超过10个),则可以使用

    String[] array = new String[]{"0", "1", "2"};
    String orig = "this is $0 string some text here $1 another text here $2 and some here";

    StringBuffer b = new StringBuffer(orig);
    int lastIndex = -2;
    for (int i = 0; i < array.length; i++) {
        int i1 = orig.indexOf("$",lastIndex+2);
        b.replace(i1, i1 + 2, array[i]);
        lastIndex = i1;
    }
    String s = b.toString();

使用JHM,看来这比2-3倍快

 String.format(orig, array)

但显然并不普遍适用。 谁知道,也许(或者很可能实际上)我的代码中有一个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM