java统计句子单词个数
时间: 2023-09-11 17:11:25 浏览: 146
以下是 Java 代码,可以用于统计句子中单词的个数:
```java
public class WordCount {
public static void main(String[] args) {
String sentence = "This is a sample sentence.";
int wordCount = 0;
// Split sentence into words
String[] words = sentence.split(" ");
// Count the number of words
for (String word : words) {
wordCount++;
}
System.out.println("Word count: " + wordCount);
}
}
```
在上面的代码中,我们首先定义了一个字符串 `sentence`,它包含要统计单词数的句子。然后,我们使用 `split()` 方法将句子拆分成单词,并将这些单词存储在一个字符串数组 `words` 中。最后,我们使用一个循环来计算单词数,将每个单词计入 `wordCount` 变量中。最后,我们输出 `wordCount` 变量的值,即句子中单词的个数。
相关问题
java统计文件中单词个数
以下是一个Java程序,可以读取文件并统计其中单词的个数:
```java
import java.io.*;
public class WordCount {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
int count = 0;
while ((line = reader.readLine()) != null) {
String[] words = line.split("\\s+");
count += words.length;
}
reader.close();
System.out.println("The file contains " + count + " words.");
} catch (IOException e) {
System.err.println("Error reading file: " + e);
}
}
}
```
这个程序使用 `BufferedReader` 读取文件,然后使用 `String` 的 `split` 方法来将每一行分割成单词。我们假设单词之间使用空格进行分隔,所以使用正则表达式 `"\\s+"` 来匹配任意数量的空格。最后,我们将所有行中的单词个数相加,就得到了文件中单词的总数。
java统计句子中有多少个单词
要统计一句话中有多少个单词,可以使用Java中的String的split方法将句子分割成单词数组,然后统计单词数组的长度即可。具体实现如下:
```java
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一句话:");
String sentence = scanner.nextLine();
scanner.close();
String[] words = sentence.split("\\s+"); // 使用正则表达式将句子分割成单词数组
int count = words.length;
System.out.println("单词的个数为:" + count);
}
}
```
上述代码中,使用了正则表达式 "\\s+" 将句子分割成单词数组。这里的 "\\s+" 表示一个或多个空白字符(包括空格、制表符、换行符等)。如果需要使用其他分割规则,可以根据具体情况修改分割符。