题目描述:
编写一个程序,将输入字符串中的字符按如下规则排序。
规则 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.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.nextLine();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 26; i++)
for (char c: str.toCharArray())
if (c == i + 'a' || c == i + 'A')
sb.append(c);
for (int i = 0; i < str.length(); i++)
{
if (!((str.charAt(i) >= 'a' && str.charAt(i) <= 'z') || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')))
sb.insert(i, str.charAt(i));
}
System.out.println(sb.toString());
}
}
}
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.nextLine();
LinkedList<Character> list = new LinkedList<>();
for (char c: str.toCharArray())
{
if (Character.isLetter(c))
list.add(c);
}
Collections.sort(list, new Comparator<Character>() {
@Override
public int compare(Character o1, Character o2) {
return Character.toLowerCase(o1) - Character.toLowerCase(o2);
}
});
StringBuffer sb = new StringBuffer();
int index = 0;
for (char c: str.toCharArray())
{
if (!Character.isLetter(c))
sb.append(c);
else
sb.append(list.get(index++));
}
System.out.println(sb.toString());
}
}
}