簡體   English   中英

替換大型令牌

[英]Replace tokens in large array

我在主要班級有這段代碼

String slangOutput = msglower;
                    for (String[] replacement : sd.replacements){
                        if (slangOutput.length() == replacement[0].length()){
                            slangOutput = slangOutput.replace(replacement[0], replacement[1]);
                        }
                    }

並在slangDictionary類中具有> 5000個數組:

String [][] replacements ={
            {"*4u","kiss for you"},
            {"*67"," unknown"},
            {"*eg*","evil grin"},
            {"07734","hello"},
            {"0day","software illegally obtained before it was released"},
            {"0noe","oh no"},
......

我非常確定java的數組大小有限,並且當我運行此代碼時,它僅替換1000個第一個數組。 如何處理並優化計算。 謝謝你的幫助

Java數組的最大大小不受1000的限制-檢查數組的length屬性,它是int類型的。 在不檢查規格的情況下,理論上它是2 ^ 31-1 = 2147483647,即Integer.MAX_VALUE。 因此,您不會在1000個元素后達到最大大小-它在其他位置(內存?)

除非您大約達到Integer.MAX_VALUE,否則Java數組的大小不受限制。 那不是問題。

第一個問題是您使用了錯誤的數據結構。 這不是數組的用途。 您希望將一些字符串映射到其他字符串,因此,正是使用映射的情況。 您的replacements應為Map<String, String> ,尤其是使用HashMap實現。 您可以使用靜態初始化程序填充地圖-在您的類中,例如

private static Map<String, String> replacements;
static {
   replacements = new HashMap<String, String>();
   replacements.put("*4u", "kiss for you");
   .....
}

然后,字符串的replace方法不是很快。 在不需要使用大量代碼的情況下需要進行一些替換時,這是很好的,但是如果您成千上萬次地循環使用它,那真的很糟糕。 一種加快速度的方法是使用StringBuilder

StringBuilder sb = new StringBuilder(msglower);
for (Entry<String, String> replacement : replacements.entrySet()) {
  int start = sb.indexOf(replacement.geyKey(), 0);
  while (start >= 0) {
    int end = start + replacement.getKey().length();
    sb.replace(start, end, replacement.getValue());
    start = sb.indexOf(replacement.getKey(), start + replacement.getValue().length());
  }
}

我沒有嘗試編譯以上內容,但這應該是正確的想法。 並以這種方式使用StringBuilder將使替換運行得更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM