请问在java中如何对中文字符进行排序呢?

sdsuper 2002-10-11 12:55:50
String str1="中国";
String str2="北京";
String str3="亚运会";
如何按照升序或降序为这个3个字符串排序?
java中有这样的函数吗?
...全文
423 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdsuper 2002-10-11
  • 打赏
  • 举报
回复
楼上的大哥。
我是java初学,谢谢了。
结帖给分。呵呵
ChDw 2002-10-11
  • 打赏
  • 举报
回复
我这个排序是按照GB2312的顺序进行排列,基本上会按照拼音排序的
我没有做优化,重复次数较多。你可以改进改进。
public class Test {
public static class PYComparator implements Comparator{
public int compare(Object o1,Object o2) {
try {
byte[] buf1 = ((String)o1).getBytes("GB2312");
byte[] buf2 = ((String)o2).getBytes("GB2312");
int size = Math.min(buf1.length,buf2.length);
for(int i = 0; i < size; i++) {
if(buf1[i] < buf2[i])
return -1;
else if(buf1[i] > buf2[i])
return 1;
}
return buf1.length - buf2.length;
}
catch (UnsupportedEncodingException ex) {
return 0;
}
}
}
public static void main(String[] args) throws Exception{
String[] str = {"北京","中国","亚运会"};
Arrays.sort(str,new PYComparator());
for(int i = 0 ; i < str.length; i++)
System.out.println(str[i]);
}
}
sdsuper 2002-10-11
  • 打赏
  • 举报
回复
高手出招呀~~~~!~!~
tomxutomxu 2002-10-11
  • 打赏
  • 举报
回复
"中啊".compareTo("中国")
sdsuper 2002-10-11
  • 打赏
  • 举报
回复
不是按照长度。是按照汉语拼音
如上面的例子,
结果要为

北京------(beijing)
亚运会-----(yayunhui)
中国--------(zhongguo)

xue_sharp 2002-10-11
  • 打赏
  • 举报
回复
你说的排序是什么意思?是按字符串长度吗?
要是按长度排序我有。
public class SortUtil
{
public SortUtil()
{
}

protected static void swap2( String[] x, int a, int b )
{
String t = x[ a ];
x[ a ] = x[ b ];
x[ b ] = t;
}

protected static void sortArrys( String[] a )
{
String temp;

for ( int i = 0; i < ( a.length / 2 ); i++ )
{
temp = a[ a.length - i - 1 ];
a[ a.length - i - 1 ] = a[ i ];
a[ i ] = temp;
}

return;
}

/**
* 对string数组按其中string长度由长到短排序
* @param String[]
*/
public static void sortByStrLength( String[] s )
{
// Insertion sort on smallest arrays
int[] is = new int[ s.length ];
int off = 0;
int len = is.length;

for ( int i = 0; i < is.length; i++ )
{
is[ i ] = s[ i ].getBytes().length;
}

if ( true )
{
for ( int i = off; i < len + off; i++ )
{
for ( int j = i; j > off && is[ j - 1 ] > is[ j ]; j-- )
{
swap2( s, j, j - 1 );

for ( int h = 0; h < is.length; h++ )
{
is[ h ] = s[ h ].getBytes().length;
}
}
}

sortArrys( s );

return;
}
}

public static void main( String[] args )
{
String[] s = {
"中", "bbbb", "cc", "d", "eeeee", "ff", "asdfda", "eef", "de",
"cc中国", "中国人", "卧室中国"
};
sortByStrLength( s );

for ( int k = 0; k < s.length; k++ )
{
System.out.println( s[ k ] );
}
}
}
kofwr 2002-10-11
  • 打赏
  • 举报
回复
应该是按unicode来排序吧.

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧