Java Program Input - "Welcome1","round4","1st3","to2" => output - "Welcome1","to2","1st3","round4"
import java.util.Arrays;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class sortingStringUsingLastChar {
public static void main(String[] args) {
String[] inputArray = {"Welcome1", "round4", "1st3", "to2"};
System.out.println("Original Array: " + Arrays.toString(inputArray));
// Sort the array using a custom comparator
Arrays.sort(inputArray, new NumericStringComparator());
System.out.println("Sorted Array: " + Arrays.toString(inputArray));
}
/**
* A custom Comparator for sorting alphanumeric strings by the integer value they contain.
*/
static class NumericStringComparator implements Comparator<String> {
// Pattern to find the first sequence of digits in a string
private static final Pattern intsOnly = Pattern.compile("\\d+");
@Override
public int compare(String s1, String s2) {
Integer num1 = extractNumber(s1);
Integer num2 = extractNumber(s2);
// If both strings have numbers, compare them numerically
if (num1 != null && num2 != null) {
return Integer.compare(num1, num2);
}
// Fall back to natural string comparison if numbers aren't found or an issue occurs
return s1.compareTo(s2);
}
/**
* Extracts the first integer found in the given string.
* @param s The input string.
* @return The extracted integer, or null if no integer is found.
*/
private Integer extractNumber(String s) {
Matcher matcher = intsOnly.matcher(s);
if (matcher.find()) {
try {
return Integer.parseInt(matcher.group());
} catch (NumberFormatException e) {
// Handle potential parsing errors gracefully
return null;
}
}
return null;
}
}
}
output:Original Array: [Welcome1, round4, 1st3, to2]
Sorted Array: [Welcome1, 1st3, to2, round4]
Comments
Post a Comment