日期:2014-05-20  浏览次数:20759 次

Java中关于字符串的一道面试题
编码实现 将10个字符串中的数字类型和字符类型加以区别,数字类型按大小排序,字符类型按长度排序

------解决方案--------------------
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class StrAndIntCount {
static List<Integer> intList=new ArrayList<Integer>();
static List<String> strList=new ArrayList<String>();
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.println("请输入你的"+(i+1)+"个字符串:");
String str=console.nextLine();
spit(str);
}
sort();
showList();
}
/**演示排序的集合*/
private static void showList() {
System.out.println("整数的排序:");
for(int a : intList){
System.out.print(a+", ");
}
System.out.println();
System.out.println("字符串的排序:");
for(String b : strList){
System.out.print(b+", ");
}
}
/**1,整数集合按从大到小排序
* 2,字符结合按字符串长度排序
* */
private static void sort() {
//整数集合排序
Collections.sort(intList, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2-o1;
}

});
//字符集合排序
Collections.sort(strList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.length()-o1.length();
}
});
}
/**判断用户输入的字符类型*/
private static void spit(String str) {
String regInt="^\\d*$";
if(str.matches(regInt)){
int intStr=Integer.parseInt(str);
intList.add(intStr);
}
else{
strList.add(str);
}

}

}

------解决方案--------------------
不知道是不是你想要的
Java code

package com.zf.thread;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
public class Thread4 {

    public static void main(String[] args) {

        String[] strs = new String[]
                {"fdasfa","fda" ,"321","432","222" 
                ,"343","5k321","643jk432" ,"fsds"};

        LinkedList<String> linkedList = new LinkedList<String>();
        int numeralSize = 0 ;    //记录数字的个数
        for (String s : strs) {
            if(s.matches("\\d+")){
                linkedList.addFirst(s);    //数字放前
                numeralSize++;
            }else{
                linkedList.addLast(s);  //字符串放后
            }
        } 
        
        strs = linkedList.toArray(new String[linkedList.size()]);
        
        Arrays.sort(strs, 0 , numeralSize, new NumeralComparator());
        Arrays.sort(strs, numeralSize , strs.length, new StringComparator());
        
        //排序后
        for (String string : strs) {
            System.out.println(string);
        }
         
    }

}

/**
 * 数字类型比较器
 * @author zhoufeng
 */
class NumeralComparator implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
        return Integer.valueOf(o1) - Integer.valueOf(o2); 
    }    
}

/**
 * String类型比较器
 * @author zhoufeng
 */
class StringComparator implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
        return o1.length() - o2.length(); 
    }    
}