使用java语言,现要求去除所有非 a-z 与 A-Z 的字符,并转换为小写 ,比如 award. This's great. 结果应为 award 、 this 、 s 和 great 单词。
时间: 2024-03-18 18:39:49 浏览: 10
好的,以下是 Java 代码示例:
```
String text = "award. This's great.";
text = text.replaceAll("[^a-zA-Z\\s]", ""); // 去除非 a-z 和 A-Z 的字符
text = text.toLowerCase(); // 转换为小写
String[] words = text.split("\\s+"); // 拆分为单词
for (String word : words) {
System.out.println(word);
}
```
这个程序使用了 `replaceAll()` 方法来去除所有非 a-z 和 A-Z 的字符,使用 `toLowerCase()` 方法将所有字母转换为小写,并使用 `split()` 方法将文本拆分为单个单词。最后,使用 `for` 循环遍历所有单词,并将其打印出来。
相关问题
用java语言 请定义一个方法,返回任意的a-z的字符,提示:小写a对应的ASCII是97;
好的,以下是使用 Java 语言定义返回任意 a-z 字符的方法:
```java
import java.util.Random;
public class RandomCharGenerator {
public static char getRandomChar() {
Random random = new Random();
int asciiValue = random.nextInt(26) + 97; // 生成97到122之间的随机数
return (char) asciiValue;
}
public static void main(String[] args) {
char randomChar = getRandomChar();
System.out.println(randomChar);
}
}
```
这个方法使用 `java.util.Random` 类来生成一个随机数,然后将其加上 97,得到一个范围在 97 到 122 之间的整数值。最后,将这个整数强制转换为字符类型,并将其返回作为结果。在 `main` 方法中,我们调用 `getRandomChar` 方法并打印结果。
java中a z正则表达式,Java正则字符类[a-zA-Z]匹配
Java中的正则表达式可以使用字符类来匹配字母。要匹配所有小写和大写字母,可以使用[a-zA-Z]字符类。例如,以下代码将匹配字符串中的所有字母:
```
String str = "Hello World!";
String pattern = "[a-zA-Z]+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
while (m.find()) {
System.out.println("Match: " + m.group(0));
}
```
在这个例子中,我们使用正则表达式`[a-zA-Z]+`来匹配一个或多个字母。然后我们使用`Pattern`类和`Matcher`类来执行匹配操作,最后打印所有匹配的结果。输出将是:
```
Match: Hello
Match: World
```