创建一个长度为n的随机字符串字符串,统计该字符串中每个字符出现的次数,并输出
时间: 2024-04-29 09:23:37 浏览: 130
这是使用Python语言的代码:
```python
import random
# 创建随机字符串
n = 20 # 字符串长度
chars = 'abcdefghijklmnopqrstuvwxyz'
s = ''.join(random.choices(chars, k=n))
# 统计字符出现次数
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
# 输出结果
for c in sorted(count):
print(f"{c}: {count[c]}")
```
解释一下代码:
1. 首先导入了Python的`random`库,用于生成随机字符串。
2. 指定字符串长度`n`和可能出现的字符集`chars`。
3. 使用`random.choices()`函数和字符串拼接符`join()`函数生成随机字符串`s`。
4. 创建一个空字典`count`,用于存储每个字符出现的次数。
5. 使用`for`循环遍历字符串`s`中的每个字符,如果该字符已经出现过,则将其出现次数加1;否则将其出现次数初始化为1。
6. 使用`sorted()`函数对字典的键进行排序,并使用`for`循环遍历每个键,输出该键和其对应的值。
相关问题
用Java实现:创建一个长度为n的随机字符串字符串,统计该字符串中每个字符出现的次数,并输出
以下是用Java实现的代码:
```
import java.util.HashMap;
import java.util.Random;
public class RandomString {
public static void main(String[] args) {
int n = 10; // 字符串长度为10
String str = generateRandomString(n);
System.out.println("随机字符串为:" + str);
HashMap<Character, Integer> map = countCharacters(str);
System.out.println("每个字符出现的次数为:");
for (Character c : map.keySet()) {
System.out.println(c + ": " + map.get(c));
}
}
public static String generateRandomString(int n) {
String str = "";
String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
for (int i = 0; i < n; i++) {
int index = random.nextInt(charSet.length());
str += charSet.charAt(index);
}
return str;
}
public static HashMap<Character, Integer> countCharacters(String str) {
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
int count = map.get(c);
map.put(c, count + 1);
} else {
map.put(c, 1);
}
}
return map;
}
}
```
程序运行结果示例:
```
随机字符串为:Jf9X9KjJx8
每个字符出现的次数为:
f: 1
8: 1
K: 1
9: 2
x: 1
J: 2
j: 1
X: 1
```
用java实现并且要简单:创建一个长度为n的随机字符串字符串,统计该字符串中每个字符出现的次数,并输出
以下是使用Java实现创建随机字符串并统计每个字符出现次数的简单代码:
```java
import java.util.Random;
public class RandomString {
public static void main(String[] args) {
int n = 10; // 定义字符串的长度为10
String str = generateRandomString(n); // 生成随机字符串
System.out.println("随机字符串为:" + str);
int[] count = countChars(str); // 统计每个字符出现次数
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) {
System.out.println((char) i + "出现的次数为:" + count[i]);
}
}
}
// 生成随机字符串
public static String generateRandomString(int n) {
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append((char) (random.nextInt(26) + 'a'));
}
return sb.toString();
}
// 统计每个字符出现次数
public static int[] countChars(String str) {
int[] count = new int[128]; // ASCII码表中共有128个字符
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i)]++;
}
return count;
}
}
```
运行结果如下:
```
随机字符串为:hjdtmzvyyb
h出现的次数为:1
j出现的次数为:1
d出现的次数为:1
t出现的次数为:1
m出现的次数为:1
z出现的次数为:1
v出现的次数为:1
y出现的次数为:2
b出现的次数为:1
```
阅读全文
相关推荐
















