Java Jave初学者-计算字符串中的单词数
我试图编写一段代码,接收一个字符串作为输入,然后计算该字符串中的字数,但不管输入是什么,它都返回1。令人惊讶的是,粘贴我课本中的示例代码(C.Thomas Wu——面向对象编程入门)也会遇到同样的问题,我不知道为什么 我的代码如下:Java Jave初学者-计算字符串中的单词数,java,Java,我试图编写一段代码,接收一个字符串作为输入,然后计算该字符串中的字数,但不管输入是什么,它都返回1。令人惊讶的是,粘贴我课本中的示例代码(C.Thomas Wu——面向对象编程入门)也会遇到同样的问题,我不知道为什么 我的代码如下: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(S
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String sentence = scanner.next();
char BLANK = ' ';
int index = 0, wordCount = 0;
int numberOfCharacters = sentence.length();
while (index < sentence.length()){
while (index < sentence.length() && sentence.charAt(index) != BLANK){
index++;
}
while (index < sentence.length() && sentence.charAt(index) == BLANK){
index++;
}
wordCount++;
}
System.out.println(wordCount);
}
}
导入java.util.Scanner;
公共班机{
公共静态void main(字符串[]args){
扫描仪=新的扫描仪(System.in);
System.out.println(“输入一个句子:”);
字符串语句=scanner.next();
字符空白=“”;
int index=0,wordCount=0;
int numberOfCharacters=句子长度();
while(索引<句子长度()){
while(索引<句子长度()&&句子字符(索引)!=空白){
索引++;
}
while(索引<句子.长度()&&句子.字符(索引)=空白){
索引++;
}
字数++;
}
System.out.println(字数);
}
}
提前感谢您的帮助 Scanner.next只返回一个“单词”(对于单词的某些定义),每次调用它都会返回输入中的下一个单词 要获得包含多个单词的整行文本,请使用
nextLine
:
String sentence = scanner.nextLine();
您好,您可以使用
语句。拆分(“”)
并获取长度
例如:
String-sense=“我每天都喜欢吃苹果”;
字符串[]单词=句子。拆分(“”);
int wordCount=words.length;
您可以使用正则表达式计算所有类型的空格,包括超过1个连续空格字符、制表符和换行符:
\\s是一个与空格字符匹配的正则表达式
.split():
根据分隔符/分隔符(即\\s+
正则表达式)将字符串拆分为不同的字符串
String sentence = scanner.next();
String[] split= sentence.split("\\s+");
int wordCount = split.length;
System.out.println(wordCount);
检查字符串中字数的代码:
String语句=“我是Java的新用户!”;
int word_count=0;
对于(inti=1;i<句子长度();i++){
char ch=句子charAt(i);
char ch2=句子charAt(i-1);
如果(ch=''&&ch2!='')
字数++;
}
System.out.println(“字数:”+字数);
输出:
字数:4
您已经使用了scanner.next()
,它将只捕获句子的第一个单词。它在找到空白处停止。您需要使用scanner.nextLine()
此外,下面给出了另一种方法:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
System.out.println("Total no. of words: " + scanner.nextLine().split("\\s+").length);
}
}
运行示例:
Enter a sentence: Ram is a good boy.
Total no. of words: 5
Enter a sentence: Harry is an intelligent guy.
Total no. of words: 5
另一个示例运行:
Enter a sentence: Ram is a good boy.
Total no. of words: 5
Enter a sentence: Harry is an intelligent guy.
Total no. of words: 5
在这个程序中,我们使用
String::split
函数在空格上拆分输入,该函数返回一个String[]
,并将输入的单词作为其元素,然后我们打印得到的String[]
的长度,你是说什么?哎呀,我没有意识到我一直在使用scanner.next()
一直以来。谢谢另外,使用nextLine()将输入整个文本,而不仅仅是单词(请参阅其他答案)