精華區beta java 關於我們 聯絡資訊
※ 引述《Dancer31 (:p)》之銘言: : 想把 String的 5,000轉成 5000 : 也就是去掉逗號 : 有函式可以套嗎? : 感謝~ 呃... 大家都說去掉 comma 再用 Integer.parse 那我就提議一個另類一點的 (也就是沒事找事幹來著 XD) DecimalFormat 是個好物 XD 不過 Exception 要 catch 好,不要像叔叔我這麼懶惰 XD public static void main(String argv[]) throws Exception { String strTMP = "13,424,555"; String pattern = "#,###"; java.text.DecimalFormat dfmt = new java.text.DecimalFormat(pattern); Number parsedNum = dfmt.parse(strTMP); System.out.println(parsedNum.intValue()); } -- 很多人以為 所以我要 其實我是個快 我是大學生 告訴大家 三十歲的怪叔叔 ● ●/ ︿ ︿ /\ < ● ㄨ /\ ㄨ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.218.142.161 > -------------------------------------------------------------------------- < 作者: superlubu (勁過呂布) 看板: java 標題: Re: [問題] parse 數字 時間: Tue Jul 3 15:24:26 2007 ※ 引述《archerlin ()》之銘言: : 哈,你少了一個轉成int的步驟啦~ : 這樣只是印出來看起來對但還是存在String[]裡阿 : 並不能變成一個整數來做之後程式需要的運算...... : 要是我我也是只會立即想到這行最簡單的作法啦 (像PsMonkey版主的想法) : int i = Integer.parseInt("123,456,789".replace(",", "")); : 那篇被M的我測過效率還是沒有上面這行快, : 但是有時候練習程式也不是光看速度、效率這些東西的... 其實如果論速度,每次只 parse 一次 DecimalFormat 的確是比不上 replaceAll 再 Integer.parseInt 的。 (注意: 是用 replaceAll, 因 replace 是 replace character only... 我使用 JDK1.5 中) 不過當會重覆使用很多次的話,用一個 static 的 DecimalFormat Object 會比重 覆的 call replaceAll 來得快。 而如果假設輸入的 string 只能是正數,且不理會 , 的出現格式,還是使用化石級 的 primitive 處理法最快... 以下補上吃飽沒事做的程式碼 XD public static void main(String argv[]) throws Exception { int noftime = 100000; String strTMP = "13,424,555"; String pattern = "#,###;(#,###)"; Number parsedNum = null; int num = 0; long t = System.currentTimeMillis(); java.text.DecimalFormat dfmt = new java.text.DecimalFormat(pattern); for (int i=0; i<noftime; i++) parsedNum = dfmt.parse(strTMP); System.out.println("D. Format: " + (System.currentTimeMillis() - t) + "ms"); t = System.currentTimeMillis(); for (int i=0; i<noftime; i++) num = Integer.parseInt(strTMP.replaceAll(",","")); System.out.println("parseInt: " + (System.currentTimeMillis() - t) + "ms"); int result = 0; t = System.currentTimeMillis(); for (int i=0; i<noftime; i++) { result = 0; for (int j=0; j<strTMP.length(); j++) { char c = strTMP.charAt(j); if (c == ',') continue; if ( c < '0' || c > '9' ) throw new IllegalArgumentException("Unexpected character: " + c); result *= 10; result += (int) c - '0'; } } System.out.println("Primitive" + (System.currentTimeMillis() - t) + "ms"); } 得出結果是: D.Format: 297ms parseInt: 640ms Primitive: 16ms 還是 primitive 王道 XD 不過值得商榷,有多少個程式需要這樣十萬次呢?我不斷將 noftime 調低,看看到 了多少次,才會令 D.Format 和 parseInt 平手 (好啦,我們就別理 Primitive 這蠻牛了 XD) 一下子將 noftime 降到 25000: D.Format: 156ms parseInt: 219ms Primitive: 0ms 看到兩方都已經非常地接近了 (啊不是說好不提 Primitive 嗎) 繼續實驗的結果是,當 noftime 介乎 1500 - 2000 的時候,兩者的耗用時間就差不 多了,而當 noftime 比 1000 為低時,parseInt 就肯定會比 D.Format 有效率... 如果沒有 Primitive 比來攪局的話 XDrz 不過仍然強調,在實驗中只有 new 過一次 DecimalFormat。如果程式不容許有一個共 用的 DecimalFormat instance,那就沒話說了 :D -- 很多人以為 所以我要 其實我是個快 我是大學生 告訴大家 三十歲的怪叔叔 ● ●/ ︿ ︿ /\ < ● ㄨ /\ ㄨ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.218.142.161 ※ 編輯: superlubu 來自: 203.218.142.161 (07/03 15:25)