dingfirst

On the Road

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  8 随笔 :: 2 文章 :: 3 评论 :: 0 Trackbacks
 1     public static int compare(String str1, String str2)
 2     {
 3         int result = 0;
 4         String m_s1 = null;
 5         String m_s2 = null;
 6         try
 7         {
 8             m_s1 = new String(str1.getBytes(_FromEncode_), _ToEncode_);
 9             m_s2 = new String(str2.getBytes(_FromEncode_), _ToEncode_);
10         }

11         catch(Exception e)
12         {
13             return str1.compareTo(str2);
14         }

15         result = chineseCompareTo(m_s1, m_s2);
16         return result;
17     }

18
19     public static int getCharCode(String s)
20     {
21         if(s == null && s.equals(""))
22             return -1;
23         byte b[] = s.getBytes();
24         int value = 0;
25         for(int i = 0; i < b.length && i <= 2; i++)
26             value = value * 100 + b[i];
27
28         return value;
29     }

30
31     public static int chineseCompareTo(String s1, String s2)
32     {
33         int len1 = s1.length();
34         int len2 = s2.length();
35         int n = Math.min(len1, len2);
36         for(int i = 0; i < n; i++)
37         {
38             int s1_code = getCharCode(s1.charAt(i) + "");
39             int s2_code = getCharCode(s2.charAt(i) + "");
40             if(s1_code * s2_code < 0)
41                 return Math.min(s1_code, s2_code);
42             if(s1_code != s2_code)
43                 return s1_code - s2_code;
44         }

45
46         return len1 - len2;
47     }

算是比较准的了,但还是有错误,而且性能比较差。

算法最初是谁写的也忘了。呵呵,拿来用一下.
posted on 2006-07-11 15:18 dingfirst 阅读(238) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: