本帖最后由 猫腻 于 2013-3-13 15:04 编辑
- int compareTo(String str)字符串比较的结果及其含义
- 值 含义
- 小于0 调用字符串小于str
- 大于0 调用字符串大于str
- 等于0 两个字符串相等
- 下面是一个对字符串数组进行排序的例子程序。程序中在冒泡法排序中使用
- compareTo( )方法确定排序的顺序:
- // A bubble sort for Strings.
- class SortString {
- static String arr[] = {
- "Now", "is", "the", "time", "for", "all", "good", "men",
- "to", "come", "to", "the", "aid", "of", "their", "country"
- };
- public static void main(String args[]) {
- for(int j = 0; j < arr.length; j++) {
- for(int i = j + 1; i < arr.length; i++) {
- if(arr.compareTo(arr[j]) < 0) {
- String t = arr[j];
- arr[j] = arr;
- arr = t;
- }
- }
- System.out.println(arr[j]);
- }
- }
- }
- 程序的输出是如下的单词表:
- Now
- aid
- all
- come
- country
- for
- good
- is
- men
- of
- the
- the
复制代码 |