我正在尝试制作一个关于字数的程序,我已经部分制作并且它给出了正确的结果但是当我输入空格或字符串中的多个空格时,字数的结果显示错误的结果,因为我我根据使用的空格计算单词。如果有一个解决方案,无论有多少空格,我仍然得到正确的结果,我需要帮助。我提到下面的代码。
I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.
public class CountWords { public static void main (String[] args) { System.out.println("Simple Java Word Count Program"); String str1 = "Today is Holdiay Day"; int wordCount = 1; for (int i = 0; i < str1.length(); i++) { if (str1.charAt(i) == ' ') { wordCount++; } } System.out.println("Word count is = " + wordCount); } }推荐答案
public static void main (String[] args) { System.out.println("Simple Java Word Count Program"); String str1 = "Today is Holdiay Day"; String[] wordArray = str1.trim().split("\\s+"); int wordCount = wordArray.length; System.out.println("Word count is = " + wordCount); }
想法是将字符串拆分为任何数字出现的任何空格字符时代 String类的split函数返回一个包含单词作为元素的数组。 打印数组的长度会产生字符串中的单词数。
The ideas is to split the string into words on any whitespace character occurring any number of times. The split function of the String class returns an array containing the words as its elements. Printing the length of the array would yield the number of words in the string.
更多推荐
Java字数统计程序
发布评论