First of all a, e
and g
are variables and not necessarily strings. What you mean is probably "a", "e"
and "g"
.
Your question is essentially:
How do I sort the values in a
String[]
so that numbers are sorted numerically and prioritized before letters (or words?) which are sorted alphabetically?
Your question seems incomplete, though. How would you sort strings like "15qwe"
or "asd34"
? Since these could be interpreted in different ways and you haven’t told us the rules for these I will ignore these and help you with the case of only numbers and only letters.
There is a class called Integer
that has a static method called parseInt()
. If the argument to this method does not contain any integers it will throw an exception, so it is a simple way for you to check if it is a number or letter.
For example:
String[] arr = {"5", "7", "a", "1", "g", "b"};
String[] numberArray = new String[3];
// keep this as a String[] for simpler concatenation of the arrays later
String[] stringArr = new String[3];
/*if you do not know that there will be exactly 3 of each,
just write arr.length isntead of 3*/
for(int i = 0; i < arr.length; i++) {
int numberIndex = 0;
int stringIndex = 0;
try {
Integer.parseInt(arr[i]);
numberArray[numberIndex] = arr[i];
numberIndex++;
} catch (Exception e) {
String s = arr[i];
stringArr[stringIndex] = s;
stringIndex++;
}
}
Arrays.sort(stringArr);
Arrays.sort(numberArray);
Now all you have to do is to concatenate the two arrays into one.
// you can replace numberArray.length and stringArr.length with 3 if you want
for(int i = 0; i < numberArray.length; i++) {
arr[i] = numberArray[i];
}
for(int i = 0; i < stringArr.length; i++) {
arr[numberArray.length + i] = stringArr[i];
}
System.out.println(Arrays.toString(arr));
Mistake found:
Since the numberArray is a String[]
it will still sort alphabetically and not numerically. If you for example have "3", "1"
and "15"
, it will sort them in this order: {"1", "15", "3"}
. This is probably not what you want, so it was a mistake on my part to have a String[]
instead of an int[]
.
So what you need to do is to implement these changes to the code:
-
int[] numberArray = new int[3];
instead ofString[] numberArray = new String[3];
-
numberArray[numberIndex] = Integer.parseInt(arr[i]);
instead of:Integer.parseInt(arr[i]); numberArray[numberIndex] = arr[i];
When you are going to concatenate the arrays later, you need to convert the integers to strings again. This is easily done with the static method Integer.toString()
.
So you need to make this small change to the code as well:
arr[i] = Integer.toString(numberArray[i]);
instead of arr[i] = numberArray[i];
2
solved Write a function that will sort a string array using Java