Java implements alphabetical sorting in strings and outputs the sorted results
1. Create a string, assign a value and Store characters into an array one by one.
String str = "chenughonghuiaikuangwantong1314"; char[] chars = str.toCharArray();
2. Sort it
The sort method is a static method in the Arrays class and can be called directly using the class name.
static void sort(type [] a)
Sort the specified type array in ascending numerical order.
The default is ascending order
static void sort(type [] a, int fromIndex, int toIndex)
Sort the specified range of the specified array in ascending numerical order.
type
can be specified as int, float, double, long, byte, etc.
##a - The array to be sorted
fromIndex - The index of the first element to be sorted (inclusive)
toIndex-The index of the last element to be sorted (exclusive)
3. Print the loop through the for loop
Forward printingfor (int i = 0; i < chars.length; i++) { System.out.print(chars[i]); }
for (int i = chars.length - 1; i >= 0; i--) { System.out.print(chars[i]); }
import java.util.Arrays; public class characterSorting { public static void main(String[] args) { String str = "chenughonghuiaikuangwantong1314"; System.out.println("原字符串:"+str); char[] chars = str.toCharArray(); Arrays.sort(chars); //正序遍历输出 System.out.println("正序输出:"); for (int i = 0; i < chars.length; i++) { System.out.print(chars[i]); } //倒序遍历输出 System.out.println(); System.out.println("倒序输出:"); for (int i = chars.length - 1; i >= 0; i--) { System.out.print(chars[i]); } } }
The above is the detailed content of How to implement alphabetical sorting in strings in java. For more information, please follow other related articles on the PHP Chinese website!