假设-1
和-5
是int
一个简单的解决方案:
public String sortStringWithInts(String input){
String[] parts = input.split("\\s");
List<String> strings = new ArrayList<String>();
List<Integer> ints = new ArrayList<Integer>();
for(String part:parts){
if(isNumber(part)){
ints.add(Integer.valueOf(part));
}
else{
strings.add(part);
}
}
Collections.sort(strings);
Collections.sort(ints);
return createResult(strings, ints, parts);
}
private String createResult(List<String> strings, List<Integer> ints, String[] parts) {
StringBuilder result = new StringBuilder();
for(String part:parts){
if(isNumber(part)){
result.append(ints.remove(0)).append(" ");
}
else{
result.append(strings.remove(0)).append(" ");
}
}
return result.toString();
}
private boolean isNumber(String part) {
try{
Integer.valueOf(part);
return true;
}
catch(Exception e){
return false;
}
}
注意:输出将是:apple bus -5 -1 car 3 4
因为-5 < -1
和不像你的 OP