Java中的“字符串不能以空格结尾”

时间:2013-11-01 00:58:38

标签: java

需要为名为wordCount()的方法编写方法签名,该方法接受String参数,并返回该String中的单词数。 出于这个问题的目的,“单词”是任何字符序列;它不一定是真正的英语单词。单词用空格分隔。 例如:wordCount(“Java”)应返回值1。

我编写了一段代码,但问题在于抛出异常。我有一个错误说:“包含的字符串不能以java中的空格结尾”和“包含的字符串不能以java中的空格开头” 我的尝试:

int wordCount(String s){
       if (s==null) throw new NullPointerException ("string must not be null");
      int counter=0;
        for(int i=0; i<=s.length()-1; i++){    
          if(Character.isLetter(s.charAt(i))){
             counter++;
             for(;i<=s.length()-1;i++){
                     if(s.charAt(i)==' '){
                             counter++;
                     }
             }
          }
     }
     return counter;
    } 

4 个答案:

答案 0 :(得分:1)

你的异常处理正处于正确的轨道上,但并不完全(正如你所注意到的那样)。

尝试以下代码:

public int wordCount(final String sentence) {
    // If sentence is null, throw IllegalArgumentException.
    if(sentence == null) {
        throw new IllegalArgumentException("Sentence cannot be null.");
    }
    // If sentence is empty, throw IllegalArgumentException.
    if(sentence.equals("")) {
        throw new IllegalArgumentException("Sentence cannot be empty.");
    }
    // If sentence ends with a space, throw IllegalArgumentException. "$" matches the end of a String in regex.
    if(sentence.matches(".* $")) {
        throw new IllegalArgumentException("Sentence cannot end with a space.");
    }
    // If sentence starts with a space, throw IllegalArgumentException. "^" matches the start of a String in regex.
    if(sentence.matches("^ .*")) {
        throw new IllegalArgumentException("Sentence cannot start with a space.");
    }

    int wordCount = 0;

    // Do wordcount operation...

    return wordCount;
}

正则表达式(或知识中的酷孩子的“正则表达式”)是字符串验证和搜索的绝佳工具。上述方法实现了快速失败的实现,即在执行昂贵的处理任务之前该方法将失败,无论如何都会失败。

我建议了解这里介绍的两种做法,bot正则表达式和异常处理。下面列出了一些帮助您入门的优秀资源:

答案 1 :(得分:0)

我会使用String.split()方法。这需要一个正则表达式,它返回一个包含子串的字符串数组。从那里很容易获得并返回数组的长度。

这听起来像是作业,所以我会把特定的正则表达式留给你:但它应该很短,甚至可能只有一个字符。

答案 2 :(得分:0)

我会使用splitter from google guava library。它会更正确地工作,因为标准的String.split()即使在这个简单的情况下也能正常工作:

// there is only two words, but between 'a' and 'b' are two spaces
System.out.println("a  b".split(" ").length);// print '3' becouse but it think than there is 
// empty line between these two spaces

使用番石榴,您可以这样做:

Iterables.size(Splitter.on(" ").trimResults().omitEmptyStrings().split("same  two_spaces"));// 2

答案 3 :(得分:0)

我会使用String.split()来处理这种情况。它比粘贴的代码更有效。确保检查空字符。这将有助于多个空格的句子(例如“This_sentences_has__two_spaces”)。

 public int wordCount(final String sentence) {
    int wordCount = 0;
    String trimmedSentence = sentence.trim();
    String[] words = trimmedSentence.split(" ");
    for (int i = 0; i < words.length; i++) {
        if (words[i] != null && !words[i].equals("")) {
            wordCount++;
        }
    }
    return wordCount;
}