用java实现统计以字母w开头的单词数; (2)统计单词中含“or”字符串的单词数;
时间: 2023-10-23 08:26:52 浏览: 137
1. 统计以字母w开头的单词数:
```java
public static void main(String[] args) {
String text = "Welcome to the world of Java programming. This is a wonderful language.";
String[] words = text.split("\\s+"); // 以空格分隔单词
int count = 0;
for (String word : words) {
if (word.startsWith("w") || word.startsWith("W")) { // 判断是否以w或W开头
count++;
}
}
System.out.println("以字母w开头的单词数:" + count);
}
```
输出结果:
```
以字母w开头的单词数:3
```
2. 统计单词中含“or”字符串的单词数:
```java
public static void main(String[] args) {
String text = "Welcome to the world of Java programming. This is a wonderful language.";
String[] words = text.split("\\s+"); // 以空格分隔单词
int count = 0;
for (String word : words) {
if (word.contains("or")) { // 判断是否包含“or”字符串
count++;
}
}
System.out.println("含“or”字符串的单词数:" + count);
}
```
输出结果:
```
含“or”字符串的单词数:3
```
阅读全文