分析1、创建一个字符串,赋值并将字符逐个存进数组中。
string str = "chenughonghuiaikuangwantong1314"; char[] chars = str.tochararray();
2、对其进行排序
sort方法是arrays类中的静态方法,可以直接利用类名进行调用。
static void sort(type [] a)
对指定的 type型数组按数字升序进行排序。
默认为升序排列
static void sort(type [] a, int fromindex, int toindex)
对指定数组的指定范围按数字升序进行排序。
type 可以指定为int,float,double,long,byte等
a- 要排序的数组
fromindex- 要排序的第一个元素的索引(包括)
toindex- 要排序的最后一个元素的索引(不包括)
3、通过for循环将循环打印出来
正序打印
for (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]); }
java 代码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]); } }}
运行结果
切记先写psvm!!!!!!(我在这翻沟了0.0)
以上就是java怎么实现字符串中的字母排序的详细内容。
