第七章第三十四题(对字符串的字符排序)(Character ordering of strings)
-
**7.34(对字符串的字符排序)使用以下方法头编写一个方法,返回一个排好序的字符串。
public static String sort(String s)
例如,sort(“acb”)返回abc编写一个测试程序,提示用户输入一个字符串,显示排好序的字符串。
**7.34(Character ordering of strings)Use the following method header to write a method that returns an ordered string.
public static String sort(String s)
For example, sort (“ACB”) returns ABC to write a test program that prompts the user to enter a string and displays the sorted string. -
参考代码:
package chapter07; import java.util.Scanner; public class Code_34 { public static void main(String[] args){ System.out.print("Enter a string:"); Scanner cin = new Scanner(System.in); String str = cin.nextLine(); str = sort(str); System.out.println("The sorted string is " + str); } public static String sort(String s){ char[] chs = s.toCharArray(); java.util.Arrays.sort(chs); String result = String.valueOf(chs); return result; } }
-
结果显示:
Enter a string:acb The sorted string is abc Process finished with exit code 0