java实现字符串中的字母排序并输出排序后的结果
1、创建一个字符串,赋值并将字符逐个存进数组中。
String str = "chenughonghuiaikuangwantong1314"; char[] chars = str.toCharArray();
2、对其进行排序
sort方法是Arrays类中的静态方法,可以直接利用类名进行调用。
static void sort(type [] a)
对指定的 type型数组按数字升序进行排序。
立即学习“Java免费学习笔记(深入)”;
默认为升序排列
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]); }
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怎么实现字符串中的字母排序的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号