寫教學的最大目的是教會未來的自己

String

JAVA提高String.replace() 執行速度的方法

繼續上一篇的內容,為了這些問題,我詢問了PTT 的 JAVA版,也很感謝有人替我解答,並教我如何提高replace 的效率

參考資料 https://www.facebook.com/java.tw 的 5月8日的文章

這個方法經過測試,應該可以使用正規表示式,但我測試的次數不夠多,也不保證其效率 <-免責聲明XD

 

簡單來說 就是 JAVA 官方提供的 String 中的 replace() 把所有的任務都當成正規表示式來處理,所以效率不彰,而如果我們只是要做單純的文字置換,顯然不需要那些步驟。

以下是程式碼+口語化只有我自己懂得演算法

 

public class Replace {
	public Replace() {
		// TODO Auto-generated constructor stub
	}

	public static String replace(String str, String patten, String replacement) {
		// str 要置換的字串 把patten換成 replacement
		int pos = str.indexOf(patten);
		return pos < 0 ? str : _replace(str, patten, replacement, pos);
	}
/**演算法說明
 * 
 * @param str 資料
 * @param patten 要換掉的文字
 * @param replacement 要改成的文字
 * @param pos 那段文字在哪
 * @return 
 * 1. 從頭開始找出符合的字串,並且標示第幾個字放進pos
 * 2. 先把在pos前面的字放進結果區(newContent)
 * 3. 再放進replacement
 * 4. 再去找下一個字的位置放進pos 
 * 5. 接續步驟三直到全部找完為止
 */
	public static String _replace(String str, String patten,
			String replacement, int pos) {
		int len = str.length();
		int plen = patten.length();
		StringBuilder newContent = new StringBuilder(len);

		int lastPos = 0;

		do {
			newContent.append(str, lastPos, pos);
			newContent.append(replacement);
			lastPos = pos + plen;
			pos = str.indexOf(patten, lastPos);
		} while (pos > 0);
		newContent.append(str, lastPos, len);
		return newContent.toString();
	}
}

經過我在小說下載器上的實際測試結果

效率提高的8倍左右

以下是測試數據,以一部124頁的小說當作測試樣本

使用String.repalce() :總共花費 112890.0ms ;其中下載花費80601.0ms  資料處理花費 32289.0ms

使用新的方法             :總共花費 71188.0ms ;其中下載花費67008.0ms 資料處理花費  4180.0 ms

下載花費時間取決於測試當下的網路狀況

 

Post to Twitter Post to Plurk Post to Facebook Send Gmail

JAVA 的字串替換

參考資料

http://satellite.iteye.com/blog/224820

http://lbs.iteye.com/blog/208056

http://hehome.blogspot.tw/2011/06/java.html

 

最近為了我的小說下載器,找了很多相關的資料

 

首先 String 的 replace() 和 replaceAll()的差別

這兩個都是做string 大量置換,只是 replace() 就只是單純的置換,而replaceAll() 支援 使用正規表示式

以下是例子(抱歉引用了 參考文章的)

         
        String src = new String("ab43a2c43d");
        System.out.println(src.replace("3","f"));=>ab4f2c4fd.
        System.out.println(src.replace('3','f'));=>ab4f2c4fd.
        System.out.println(src.replaceAll("\\d","f"));=>abffafcffd.
        System.out.println(src.replaceAll("a","f"));=>fb43fc23d.
        System.out.println(src.replaceFirst("\\d,"f"));=>abf32c43d
        System.out.println(src.replaceFirst("4","h"));=>abh32c43d. .

再來就是 另一種 使用 正規表示式的 大規模置換的方法,下面的範例是用來 過濾所有的HTML 的

 
          java.util.regex.Pattern p_html;
          java.util.regex.Matcher m_html; 

          String regEx_html = "<[^>]+>"; //定義HTML標籤的正則表達式 
          p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
          m_html = p_html.matcher(htmlStr);
          htmlStr = m_html.replaceAll(""); //過濾html標籤 


我剛剛理解了 兩者之間的差別
前者的作法,每次都要重新分析一次正規表示式,而後者可以指分析一次就重複使用

Post to Twitter Post to Plurk Post to Facebook Send Gmail

Copyright © 2024. All Rights Reserved.

歡迎光臨
初音