您的位置:首页 >如何在Java中实现对字符串中的字母进行排序
发布于2023-05-10 阅读(0)
扫一扫,手机访问
java实现字符串中的字母排序并输出排序后的结果
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]);
}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)
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9