自定义Comparator比较String字符串

package sn.len.demo;

import java.util.Arrays;
import java.util.Comparator;
//一般用Arrays.sort都按一个一个的字符去比较的,而不是按照自己所想根据Ascii去比较的,所以。。。。
public class ArrayStore
{
	public static void main(String[] args)
	{
		String str[] = new String[5];
		str[0] = "OPS/chapter5.html";
		str[1] = "OPS/chapter4.html";
		str[2] = "OPS/chapter69.html";
		str[3] = "OPS/chapter7.html";
		str[4] = "OPS/chapter27.html";

		Arrays.sort(str, htmlComp);
		for (int i = 0; i < str.length; i++)
		{
			System.out.println(str[i]);
		}

	}
	private static Comparator htmlComp = new Comparator()
	{
		@Override
		public int compare(String o1, String o2)
		{
			if (o1.startsWith("OPS/chapter") && o2.startsWith("OPS/chapter"))
			{
				System.out.println("o1---->"+o1);
				System.out.println("o2---->"+o2);
				String num1 = o1.substring("OPS/chapter".length(), o1.lastIndexOf(".html"));
				String num2 = o2.substring("OPS/chapter".length(), o2.lastIndexOf(".html"));
				try
				{
					Integer int1 = Integer.valueOf(num1);
					Integer int2 = Integer.valueOf(num2);
					return int1.compareTo(int2);
				} catch (Exception e)
				{
					return o1.compareTo(o2); //按字典顺序去比较两个字符串
				}
			}
			return o1.compareTo(o2);//按字典顺序去比较两个字符串
		}
	};
}

你可能感兴趣的:(自定义Comparator比较String字符串)