0

I have a String array which contains both combination of strings and integers. I need to sort the strings and add the integers at the end. Here is the program I have written. Any optimization would be helpful.

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));
}
}
}

Any help would be appreciated.

Pradeep
  • 1,947
  • 3
  • 22
  • 45

1 Answers1

0

After looking over your code for a while i cant really see any improvements other than simple syntax to reduce code length, performance wise you really have it covered as without a regex there really is not many other options for finding int's in a string other than testing each character and even the method you used assuming you pass in each line 1 at a time adheres to this performance principle:

For strings 1 to 256 characters in length, calling string.charAt(i) wins with an average processing of 13.4 million to 588 million characters per second. Source

For long strings, 512 to 256K characters length, using reflection to access the String's backing array is fastest. This technique is almost twice as fast as String.charAt(i) (178% faster). The average speed over this range was 1.111 billion characters per second.

The only suggestions i have are for readability:

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

Probably isnt any real help since the code seems to utilize best practices. Anyway good luck with your work!

Community
  • 1
  • 1
D3181
  • 2,037
  • 5
  • 19
  • 44