我有两个字符串 s1 和 s2,我想根据 s1 中字母的出现顺序对 s2 进行排序,如果其他字母留在 s2 中,则按字母顺序对它们进行排序。
假设我有以下内容;
字符串 s1 = "战争";
String s2 = "做程序员真棒";
输出:waaarrrIbeeeeggimmmnoopsst。
我已经编写了一个代码来做到这一点,但我想知道是否可以使用比较器/可比较接口来解决它。
下面列出的是我的代码片段。
public class Sort {
private static String a = "war";
private static String b = "Its awesome being a programmer";
static List<Character> list = new ArrayList<>();
static public void main(String[] args) {
Character s;
Character x;
System.out.println("String to be sorted: '" + b + "'");
System.out.println("Key for sort: '" + a + "'");
/*
* put all the string in a list
*/
for (int i = 0; i < b.length(); i++) {
s = b.charAt(i);
if (s != ' ') {
list.add(s);
}
}
/*
* compare individual chac in key with individaul char in string to sort
*/
StringBuilder sb = new StringBuilder();
for (int j = 0; j < a.length(); j++) {
x = a.charAt(j);
for (int k = 0; k < b.length(); k++) {
s = b.charAt(k);
if (x == s) {
sb.append(s);
list.remove(x);
}
}
}
/*
* check if list is empty if not, sort and append the rest to the stringbuilder
*/
if (!list.isEmpty()) {
Collections.sort(list);
for (char c : list) {
sb.append(c);
}
}
System.out.println("Sorted version of string: '" + sb.toString() + "'");
}
}