2016-07-26 39 views
0

我有一個包含字符串和整數的兩個組合的字符串數組。我需要對字符串進行排序並在最後添加整數。這是我寫的程序。任何優化都會有所幫助。StringSortingandIntegerAddition沒有正則表達式

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 

public class SortStringandAddIntegerEx { 
public static void main(String[] args) throws IOException { 
System.out.println("Enter the characters"); 
BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 
String input = read.readLine(); 
String[] inputArray = { input }; 
List<String> result = new ArrayList<String>(); 
String stringChars = ""; 
String sortedCharacters = ""; 
int sum = 0; 
for (int i = 0; i < inputArray.length; i++) { 
stringChars = stringChars + inputArray[i]; 
} 
for (int j = 0; j < stringChars.length(); j++) { 
if (Character.isDigit(stringChars.charAt(j))) { 
sum = sum + Integer.parseInt(stringChars.valueOf(stringChars.charAt(j))); 

} else { 
sortedCharacters = sortedCharacters + stringChars.charAt(j); 
} 
} 
char[] chars = sortedCharacters.toCharArray(); 
Arrays.sort(chars); 
String sorted = new String(chars); 
result.add(sorted + " " + sum); 
for (int k = 0; k < result.size(); k++) { 
System.out.println("Final output is " + result.get(k)); 
} 
} 
} 

任何幫助,將不勝感激。

回答

0

尋找你的代碼了,而我真的不能看到比簡單的語法等,以減少代碼長度的任何改進,性能明智的你真的有它覆蓋,沒有一個正則表達式那裏以後真的是查找廉政局在沒有太多其他選擇比測試每個字符和甚至該方法另一個串你用過假設你在每個線1在一個時間通過粘附到這種性能原則:

對於字符串的長度爲1〜256個字符,在調用string.charAt(I) 獲得平均處理1340萬至588萬 字符每秒。 Source

對於長字符串,512〜256K的字符長度,使用反射來 訪問字符串的底層實現數組是最快的。這種技術幾乎是 兩倍於String.charAt(i)的速度(快了178%)。在此範圍內的平均速度爲 每秒11.1億個字符。

唯一的建議,我已經是可讀性:

for (String inputArray1 : inputArray) { 
     stringChars = stringChars + inputArray1; 
    } 

也許心不是任何實際的幫助,因爲代碼似乎利用的最佳實踐。無論如何,祝你的工作順利!

+0

感謝您的建議,我會嘗試你suggested.Thanks方式 – Pradeep