java生成含26个小写英文字母的字符串,然后从中随机抽取8个字母输出
时间: 2024-05-08 20:21:35 浏览: 67
java产生由数字字母组成的随机字符
5星 · 资源好评率100%
可以使用Java的Random类生成26个小写英文字母的字符串,然后使用Random类随机抽取8个字母输出。以下是示例代码:
```java
import java.util.Random;
public class RandomString {
public static void main(String[] args) {
String alphabet = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 26; i++) {
int index = random.nextInt(alphabet.length());
char letter = alphabet.charAt(index);
sb.append(letter);
}
String randomString = sb.toString();
System.out.println("Random String: " + randomString);
System.out.print("Random 8 letters: ");
for (int i = 0; i < 8; i++) {
int index = random.nextInt(randomString.length());
char letter = randomString.charAt(index);
System.out.print(letter);
}
}
}
```
输出示例:
```
Random String: dmzquxjvckwfygatbepnslorhi
Random 8 letters: wveqzyxg
```
阅读全文