JAVA----------------华为机试-------------字符串排序
题目描述
编写一个程序,将输入字符串中的字符按如下规则排序。
规则 1 :英文字母从 A 到 Z 排列,不区分大小写。
如,输入: Type 输出: epTy
规则 2 :同一个英文字母的大小写同时存在时,按照输入顺序排列。
如,输入: BabA 输出: aABb
规则 3 :非英文字母的其它字符保持原来的位置。
如,输入: By?e 输出: Be?y
输入:
A Famous Saying: Much Ado About Nothing(2012/8).
输出:
A aaAAbc dFgghh : iimM nNn oooos Sttuuuy (2012/8).
import java.awt.List;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String string = scanner.nextLine();
LinkedList<Character> cs = new LinkedList<Character>();
for (int i = 0; i < string.length(); i++) {
Character ch = string.charAt(i);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
cs.add(ch);
}
}
String sBuilder = sortCharArr(cs);
Integer z = 0;
for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
char c = sBuilder.charAt(z++);
System.out.print(c);
} else {
System.out.print(ch);
}
}
System.out.println();
}
}
private static String sortCharArr(LinkedList<Character> linkedList) {
String str = "";
for (char c = 'a'; c <= 'z'; c++) {
char C = Character.toUpperCase(c);
Iterator<Character> iterator = linkedList.iterator();
while (iterator.hasNext()) {
Character ch = iterator.next();
if (ch == c || ch == C) {
str = str + ch + "";
iterator.remove();
}
}
}
return str;
}
}