In Java , I want to compare and sort strings that contain a character and a number. For example:
A15, D35, A17, C45, B27, C30 should be sorted
A15 A17 B27 C30 C45 D35. I am not really sure how to compare two of those elements because they contain a string and a number. Can anyone help me please?
To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.
The compare(char x, char y) method of Character class is used to compare two char values numerically. The final value returned is similar to what would be returned by: Character.
String Comparison In Java, we always use the equals() message to compare two objects – strings are just an example of that rule. For example, we used equals() to compare Color objects earlier in the quarter. The == operator is similar but is used to compare primitives such as int and char.
strcmp() in C/C++ It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.
If your numbers are always two digits, then simply compare the whole things as strings. Numbers in decimal are strings too.
It's a different story if you need to sort A9, A54, and A123456 and want the numbers to sort by their numeric value. In that case you may need to write your own compare function that splits the string apart into its component parts.
An example of said compare function:
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.google.common.collect.Lists;
class Scratch {
public static void main(String[] args) {
final List<String> in = Lists.newArrayList("D35", "A1", "C7", "A25", "A131");
Collections.sort(in, new Comparator<String>() {
@Override
public int compare(String left, String right) {
int letter = Character.compare(left.charAt(0), right.charAt(0));
if (0 != letter)
return letter;
return Long.compare(Long.parseLong(left.substring(1)), Long.parseLong(right.substring(1)));
}
});
System.out.println(in);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With