Java字数统计程序

编程入门 行业动态 更新时间:2024-10-21 14:39:50
本文介绍了Java字数统计程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试制作一个关于字数的程序,我已经部分制作并且它给出了正确的结果但是当我输入空格或字符串中的多个空格时,字数的结果显示错误的结果,因为我我根据使用的空格计算单词。如果有一个解决方案,无论有多少空格,我仍然得到正确的结果,我需要帮助。我提到下面的代码。

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字数统计程序

本文发布于:2023-11-11 07:08:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577728.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字数   程序   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!