Java生成随机字符串并统计字符出现次数
Java生成随机字符串并统计字符出现次数
本文提供一个Java代码示例,用于生成指定长度的随机字符串(仅包含大小写英文字母),并统计字符串中每个字符出现的次数。
代码示例:
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String randomString = getRandomString(15);
System.out.println(randomString);
Map<Character, Integer> charCountMap = countCharacters(randomString);
printCharacterCount(charCountMap);
}
// 生成指定长度的随机字符串
public static String getRandomString(int length) {
String characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
StringBuilder sb = new StringBuilder(length);
Random random = new Random();
for (int i = 0; i < length; i++) {
int index = random.nextInt(characters.length());
sb.append(characters.charAt(index));
}
return sb.toString();
}
// 统计字符串中每个字符出现的次数
public static Map<Character, Integer> countCharacters(String str) {
Map<Character, Integer> charCountMap = new HashMap<>();
for (char c : str.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
return charCountMap;
}
// 按字母顺序输出字符统计结果
public static void printCharacterCount(Map<Character, Integer> charCountMap) {
StringBuilder sb = new StringBuilder();
// 对Map中的字符按字母顺序排序
charCountMap.keySet().stream().sorted().forEach(key -> {
sb.append(key).append('(').append(charCountMap.get(key)).append(')');
});
System.out.println(sb.toString());
}
}
代码说明:
getRandomString(int length)方法:- 接收一个整数参数
length,表示要生成的随机字符串的长度。 - 使用
Random类生成随机索引,从预定义的字符集中选择字符,拼接成指定长度的字符串。
- 接收一个整数参数
countCharacters(String str)方法:- 接收一个字符串参数
str,表示要统计字符出现次数的字符串。 - 使用
HashMap存储每个字符及其出现的次数。 - 遍历字符串,统计每个字符出现的次数,并将结果存储到
HashMap中。
- 接收一个字符串参数
printCharacterCount(Map<Character, Integer> charCountMap)方法:- 接收一个
HashMap参数charCountMap,其中存储了字符及其出现的次数。 - 使用
stream().sorted()对HashMap中的键(字符)进行排序。 - 遍历排序后的
HashMap,将每个字符及其出现的次数格式化输出。
- 接收一个
示例输出:
XhMKZLgJwFtyulE
E(1)F(1)g(1)h(1)J(1)K(1)l(1)M(1)t(1)u(1)w(1)X(1)y(1)Z(1)
这段代码演示了如何使用Java生成随机字符串并统计字符出现次数。你可以根据自己的需求修改代码,例如更改字符集或输出格式。
原文地址: https://www.cveoy.top/t/topic/onb 著作权归作者所有。请勿转载和采集!