用字符串方法计算单词数?
我想知道如何编写一个方法来仅使用 charAt、length 或 substring 等字符串方法来计算 java 字符串中的单词数。
循环和 if 语句都可以!
我真的很感谢我能得到的任何帮助!谢谢!
I was wondering how I would write a method to count the number of words in a java string only by using string methods like charAt, length, or substring.
Loops and if statements are okay!
I really appreciate any help I can get! Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
即使使用多个空格、前导和/或尾随空格以及空行,这也适用:
有关 split 的更多信息 此处。
This would work even with multiple spaces and leading and/or trailing spaces and blank lines:
More info about split here.
嗨,我刚刚想出了这样的 StringTokenizer:
Hi I just figured out with StringTokenizer like this:
只需使用 ,
Simply use ,
使用
这个就可以了。
Use
This will work.
有一个简单的解决方案您可以尝试此代码
There is a Simple Solution You can Try this code
O(N) 中的算法
Algo in O(N)
计算字符串中的单词数:
这也可能有帮助 -->
Counting Words in a String:
This might also help -->
导入 java.util.;
导入java.io。;
公共类主要{
}
import java.util.;
import java.io.;
public class Main {
}
我对该计划的想法是:
My idea of that program is that:
我是 stackoverflow 的新手,但我希望我的代码有帮助:
I'm new to stackoverflow but I hope my code helps:
字符串短语通常由空格分隔的单词组成。那么,您可以使用空格作为分隔字符来分割短语,并按如下方式对它们进行计数。
A string phrase normaly has words separated by space. Well you can split the phrase using the spaces as separating characters and count them as follows.
以所选答案为起点,以下内容涉及一些英语语言问题,包括连字符、所有格和缩写的撇号、数字以及 UTF-16 之外的任何字符:
Taking the chosen answer as a starting point the following deals with a few English language issues including hyphenated words, apostrophes for possessives and shortenings, numbers and also any characters outside of UTF-16:
我只是把这个放在一起。 wordCount() 方法中的增量器对我来说有点不优雅,但它确实有效。
I just put this together. The incrementer in the wordCount() method is a bit inelegant to me, but it works.
创建变量计数、状态。初始化变量
如果存在空间,则保持计数,否则增加计数。
例如:
create variable count, state. initialize variables
if space is present keep count as it is else increase count.
for eg:
lambda,其中无需对计数的单词进行拆分和存储
并且仅完成计数
得到:
7< /代码>
用作状态机,计算从空格字符
.,; 开始的转换。 \t
转为单词lambda, in which splitting and storing of the counted words is dispensed with
and only counting is done
gets:
7
works as a status machine that counts the transitions from spacing characters
.,; \t
to words它将计算空格。但是,如果我们在 count 中加 1,我们就可以获得精确的单词。
It will count white spaces. However, If we add 1 in count , we can get exact words.