对字符串中的字母进行排序,变成有序的字符串

来源:互联网 发布:贵州省软件测评中心 编辑:程序博客网 时间:2024/05/17 04:44
<span style="font-size:24px;"><pre name="code" class="java">//需求:对字符串中的字母进行排序,变成有序的字符串。// "bdacxrtq" --> "abcdqrtx"; //思路://1、先把字符串变成数组//2、对数组元素进行排序//3、将数组变成字符串</span>
<span style="font-size:24px;">import java.util.Arrays;public class StringSort{public static void main(String[] args) {System.out.println("对字符串中的字母进行排序,变成有序的字符串。\"bdacxrtq\" --> \"abcdqrtx\"; ");StringSortMethodOne();  //调用方法一System.out.println("******************");StringSortMethodTwo();//调用方法二}public static void StringSortMethodOne(){  //方法一:基本思想是用冒泡排序,对字符串数组进行排序String a ="bdacxrtq";//字符串a-z可以随意设置char []arr =a.toCharArray();//用String中的方法toCharArray,字符串->字符串数组for (int i = 0; i < arr.length; i++) {//用for嵌套来交换值for (int j =i+1 ; j < arr.length; j++) {if (arr[i] >arr[j]) {char temp =arr[i];arr[i]=arr[j];arr[j]=temp;}}}String b =new String(arr);//数组转字符串System.out.println("方法一对字符串的排序是:\n"+b);//输出字符串}public static void StringSortMethodTwo(){   //方法二:用到Arrays中的sort排序方法,升序String b ="bdacxrtq";char [] arr =b.toCharArray();Arrays.sort(arr);System.out.println("方法二对字符串的排序是:");for (char c : arr) {System.out.print(c);}}}</span>


                                             
0 0