Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 查找字符串中的字数_Java - Fatal编程技术网

Java 查找字符串中的字数

Java 查找字符串中的字数,java,Java,我似乎不明白为什么这不起作用,但我可能只是错过了一些简单的逻辑。当后面没有空格时,该方法似乎找不到最后一个单词,因此我猜测i==本身.length()-1有问题,但在我看来它将返回true;您位于最后一个字符上,它不是空白 public void numWords() { int numWords = 0; for (int i = 1; i <= itself.length()-1; i ++) { if (( i == (itself.lengt

我似乎不明白为什么这不起作用,但我可能只是错过了一些简单的逻辑。当后面没有空格时,该方法似乎找不到最后一个单词,因此我猜测i==本身.length()-1有问题,但在我看来它将返回true;您位于最后一个字符上,它不是空白

public void numWords()
{
    int numWords = 0;
    for (int i = 1; i <= itself.length()-1; i ++)
    {
        if (( i == (itself.length() - 1) || itself.charAt (i) <= ' ') && itself.charAt(i-1) > ' ')
            numWords ++;
    }
    System.out.println(numWords);
}
public void numWords()
{
int numWords=0;

对于(inti=1;iNaïve approach:将后面有空格的所有内容都视为一个单词。这样,只需将元素数作为
String#split
操作的结果即可

public int numWords(String sentence) {
    if(null != sentence) {
        return sentence.split("\\s").length;
    } else {
        return 0;
    }
}
试试看


因此,基本上,你要做的就是计算一个字符串中的所有空白块。我将修复你的代码,并使用我的head编译器帮助你解决你遇到的问题

public void numWords()
{
    int numWords = 0;
    // Don't check the last character as it doesn't matter if it's ' '
    for (int i = 1; i < itself.length() - 1; i++)
    {
        // If the char is space and the next one isn't, count a new word
        if (itself.charAt(i) == ' ' && itself.charAt(i - 1) != ' ') {
            numWords++;
        }
    }
    System.out.println(numWords);
}
public void numWords()
{
int numWords=0;
//不要检查最后一个字符,因为它是否为“”
for(int i=1;i
这是一个非常简单的算法,在少数情况下会失败,如果字符串以多个空格结尾,例如
“hello world”
,它将计3个单词


请注意,如果我要实现这样一个方法,我将使用类似于Makoto答案的正则表达式方法来简化代码。

以下代码片段做得更好:

if(sentence == null) {
    return 0;
}
sentence = sentence.trim();
if ("".equals(sentence)) {
    return 0;
}
return sentence.split("\\s+").length;
  • 正则表达式
    \\s+
    在有多个空格的情况下工作正常。
    trim()
  • 删除拖尾和前导空格附加空行检查
  • 阻止空字符串的结果1

你就不能在空白处拆分吗?谢谢你的链接,我在简短的搜索中没有看到。太酷了,谢谢。我是新来的,以前从未见过。谢谢你,我感谢你的评论
if(sentence == null) {
    return 0;
}
sentence = sentence.trim();
if ("".equals(sentence)) {
    return 0;
}
return sentence.split("\\s+").length;