public class StringCom {
/**
* "avf ggh f tt dgh acd ac dg gh kl kmn" 排序
*/
public static void main(String[] args) {
String s = "avf ggh f tt dgh acd ac dg gh kl kmn";
String[] s1 = s.split(" ");
for(int i=0; i<s1.length-1; i++){
for(int j=0; j<s1.length-1-i; j++){
if(doString(s1[j],s1[j+1]) > 0){
String tem = s1[j];
s1[j] = s1[j+1];
s1[j+1] = tem;
}
}
}
StringBuffer sb = new StringBuffer();
for(int i=0; i<s1.length; i++){
sb.append(s1[i]+" ");
}
System.out.println(sb);
}
public static int doString(String s1, String s2){
int len1 = s1.length(), len2 = s2.length();
int res = len1 - len2;
int minlen = Math.min(len1, len2);
for(int i=0; i<minlen; i++){
if(s1.charAt(i) != s2.charAt(i)){
res = s1.charAt(i)-s2.charAt(i);
break;
}
}
return res;
}
}
/**
* "avf ggh f tt dgh acd ac dg gh kl kmn" 排序
*/
public static void main(String[] args) {
String s = "avf ggh f tt dgh acd ac dg gh kl kmn";
String[] s1 = s.split(" ");
for(int i=0; i<s1.length-1; i++){
for(int j=0; j<s1.length-1-i; j++){
if(doString(s1[j],s1[j+1]) > 0){
String tem = s1[j];
s1[j] = s1[j+1];
s1[j+1] = tem;
}
}
}
StringBuffer sb = new StringBuffer();
for(int i=0; i<s1.length; i++){
sb.append(s1[i]+" ");
}
System.out.println(sb);
}
public static int doString(String s1, String s2){
int len1 = s1.length(), len2 = s2.length();
int res = len1 - len2;
int minlen = Math.min(len1, len2);
for(int i=0; i<minlen; i++){
if(s1.charAt(i) != s2.charAt(i)){
res = s1.charAt(i)-s2.charAt(i);
break;
}
}
return res;
}
}
2、题稍加难度
public class PaiXuString {
/**排序中还需将小写字母一起排序,如a 要在B,b前
* 字符串排序 如 Ac Bc AcO ac 排序结果:Ac, AcO, ac, Bc
*/
public static void main(String[] args) {
String[] s = { "Bc","Ad","aC","cD","During","little","X man","day" };
String temp;
int l = s.length;
for(int i=0; i<l-1; i++){
for(int j=0; j<l-1-i;j++){
if(com(s[j],s[j+1]) > 0){
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(s));
}
public static int com(String s1, String s2){
int res = s1.length() - s2.length();
int len = Math.min(s1.length(), s2.length());
int char1code = 0, char2code =0;
char[] Char1 = s1.toCharArray();
char[] Char2 = s2.toCharArray();
for(int i=0; i<len; i++){
if(Char1[i] != Char2[i]){
char1code = Char1[i]>96? Char1[i]-96 : Char1[i] -64;
char2code = Char2[i]>96? Char2[i]-96 : Char2[i] -64;
if(char1code != char2code){
res = char1code -char2code;
break;
}else {
res = Char1[i] - Char2[i];
break;
}
}else{
continue;
}
}
return res;
}
}