java输入一段字符串,统计其中有多少个单词。
时间: 2024-06-12 20:10:25 浏览: 15
可以使用Java中的split()方法将字符串按照空格分割成字符串数组,然后统计数组的长度即可得到单词数。
示例代码如下:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一段字符串:");
String str = scanner.nextLine();
String[] words = str.split(" ");
System.out.println("单词数为:" + words.length);
}
}
```
输入示例:
```
请输入一段字符串:
Hello world, I am a Java program.
```
输出示例:
```
单词数为:7
```
相关问题
输入一段字符串,统计其中有多少个单词。(单词用空格隔开) JAVA
给定一个字符串,可以使用Java中的StringTokenizer类来将其分解为单词,然后使用countTokens()方法计算单词数。代码如下:
```
import java.util.Scanner;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
int count = st.countTokens();
System.out.println("单词数为:" + count);
}
}
```
(1) 输入一段字符串,统计其中有多少个单词。(单词用空格隔开) JAVA
输入一段字符串,统计其中有多少个单词可以使用Java中的StringTokenizer类或者split方法来实现。其中StringTokenizer类是Java中一个用于分隔字符串的类,可以指定分隔符,将字符串分割成多个子字符串。而split方法则是String类中的一个方法,可以根据指定的分隔符将字符串分割成多个子字符串,并返回一个字符串数组。下面是两种实现方式的示例代码:
使用StringTokenizer类实现:
```
import java.util.Scanner;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
int count = st.countTokens();
System.out.println("单词个数为:" + count);
}
}
```
使用split方法实现:
```
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] words = s.split(" ");
int count = words.length;
System.out.println("单词个数为:" + count);
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)