gpt4 book ai didi

java - 对字符进行排序

转载 作者:行者123 更新时间:2023-12-02 03:27:54 24 4
gpt4 key购买 nike

我正在尝试编写一个代码来计算文件中的行数和字符数,然后对任何字符(包括空格和逗号)进行排序

我想到了什么。

import java.io.BufferedReader;


File file1 = new File("C:/input.txt");
BufferedReader in = new BufferedReader(new FileReader(file1));

int nextChar;
char ch;

int[] count = new int[1000];





in.close();
}
}

提前致谢!

最佳答案

好吧,这里棘手的事情是如何按降序对原始类型 int 的数组进行排序?好吧,这个网站上有很多关于 Arrays.sort(array, Collections.reverseOrder()); 的帖子,但这只能用于对象数组,不能用于像 int。因此,最好的方法是使用内置的 Arrays 方法对数组进行升序排序,然后遍历整个数组以反转数组中的元素。因此,您应该考虑在程序末尾添加这段代码,

Arrays.sort(count);//sort in ascending order
for(int i = 0; i < count.length; i++){ //reversing the order of the array
int k = count[i]; //swapping the i-th element with the i-th to last element
count[i] = count[count.length - 1 - i];
count[count.length - 1 - i] = k;
}

就我个人而言,我建议将上面的代码放在 for 循环之前,

for (i = 0; i < 26; i++) {

System.out.printf("%c : %d", i + 'A', count[i]);

System.out.println("");
}

关于java - 对字符进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38546930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com