package StringPackage;
/*对于给定的字符串进行排序
* 字符串怎么比较?对象中提供了用于字符串比较的功能
* */
public class StringClass2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// String s1="abc";
// String s2="abc";
// intern();对字符串池进行操作的
String s1 = new String("abc");// 此对象在堆中
String s2 = s1.intern();// 对字符串池进行操作的
System.out.println(s1 == s2);
String[] arr = { "nba", "asd", "dfgh", "nba", "haha", "zz" };
printArry(arr);
sortString(arr);
printArry(arr);
}
public static void sortString(String[] arr) {
// TODO Auto-generated method stub
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i].compareTo(arr[j]) > 0) {// 字符串比较用compareTo方法完成
swp(arr, i, j);
}
}
}
}
private static void swp(String[] arr, int i, int j) {
// TODO Auto-generated method stub
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void printArry(String[] arr) {
// TODO Auto-generated method stub
System.out.print("[");//注意换行问题
for (int i = 0; i < arr.length; i++) {
if (i != arr.length - 1)
System.out.print(arr[i] + ",");
else
System.out.print(arr[i] + "]");
} System.out.println("");
}
} |
|