【问题标题】:Counting words with indexof [closed]用 indexof 计算单词
【发布时间】:2015-07-13 01:31:58
【问题描述】:

我必须计算正在阅读的博客条目中的前 1o 个单词……但我的代码不允许这种情况发生。我不能使用 .split 或 string isempty 或数组......这让我有 indexof 和子字符串。我的代码现在只得到前 3 个字......对我有任何帮助......

这是我必须使用的......

字符串 getSummary() 方法 1. 返回条目的前十个单词作为条目的摘要。如果条目有 10 个字或更少,则该方法返回整个条目。 2.可能的逻辑——String类的indexOf方法可以找到空格的位置。将其与循环结构一起使用以查找前 10 个单词。

public class BlogEntry 
{
    private String username;
    private Date dateOfBlog;
    private String blog;

    public BlogEntry() 
    {
        username = "";
        dateOfBlog = new Date();
        blog = "";
    }

    public BlogEntry(String sName, Date dBlogDate, String sBlog)
    {
        username = sName;
        dateOfBlog = dBlogDate;
        blog = sBlog;
    }

    public String getUsername()
    {
        return username;
    }

    public Date getDateOfBlog()
    {
        return dateOfBlog;
    }

    public String getBlog()
    {
        return blog;
    }

    public void setUsername(String sName)
    {
        username = sName;
    }

    public void setDateOfBlog(Date dBlogDate)
    {
        dateOfBlog.setDate(dBlogDate.getMonth(), dBlogDate.getDay(), dBlogDate.getYear());
    }

    public void setBlog(String sBlog)
    {
        blog = sBlog;
    }

    public String getSummary()
    {
        String summary = "";
        int position;
        int wordCount = 0;
        int start = 0;
        int last;

        position = blog.indexOf(" ");
        while (position != -1 && wordCount < 10)
        {
            summary += blog.substring(start, position) + " ";
            start = position + 1;
            position = blog.indexOf(" ", position + 1);
            wordCount++;
        }

        return summary;
    }

    public String toString()
    {
        return "Author: " + this.getUsername() + "\n\n" + "Date posted: " + this.getDateOfBlog() + "\n\n" + "Text body: " + this.getBlog();
    }
}

【问题讨论】:

  • 这是什么语言? (Java?)为什么你不能使用那些方法?
  • 对不起,它是 Java...
  • 我从研究中了解这些方法,但因为这是一门课程,我无法超越我们所涵盖的范围......我一直在努力解决这个问题,似乎只是无法弄清楚我是什么做错了... .split 似乎又是最简单的 ut 我不能超出我们所涵盖的范围。 :(@NathanTuggy
  • blog 可以是任何长度的任何字符串....例如“这个程序让我很生气!”可能是字符串,我的代码只是拉这个程序这就是我需要帮助的原因
  • 给出的关闭原因是错误的。戈尔迪给出了明确的问题陈述。 “我必须计算正在阅读的博客条目中的前 1o 个单词。”她提出了一个具体的问题:“只得到前 3 个单词” 问题是只有在特定输入时才成立:4 个单词。如果给定 6,它得到 5。我的编译器很好地解决了这个问题。当然,重新打开问题会带来很多好处,但这是在教 Goldie 关于 stackoverflow 的错误知识。

标签: java indexof


【解决方案1】:

将此添加到您的代码中:

public static void main(String[] args) 
{
    BlogEntry be = new BlogEntry("" , new Date(), "this program is pissing me off!");
    System.out.println( be.getSummary() );        
}

产生这个输出:

this program is pissing me

这不是 3 个单词,而是 5 个。你应该有 6 个。这让你的 bug 更容易理解。您正在体验典型的off-by-one error。您只是附加和计算空格之前的单词。这会留下最后一个单词,因为它不会出现在空格之前,只会出现在最后一个空格之后。

这里有一些接近你开始的代码,可以看到所有 6 个单词:

public String getSummary()
{
    if (blog == null) 
    {
        return "<was null>";
    }

    String summary = "";
    int position;
    int wordCount = 0;
    int start = 0;
    int last;

    position = blog.indexOf(" ");
    while (position != -1 && wordCount < 10)
    {
        summary += blog.substring(start, position) + " ";
        start = position + 1;
        position = blog.indexOf(" ", position + 1);
        wordCount++;
    }
    if (wordCount < 10) 
    {
        summary += blog.substring(start, blog.length());
    }

    return summary;
}

用这个测试时:

public static void main(String[] args) 
{
    String[] testStrings = {
          null //0
        , ""
        , " "
        , "  "
        , " hi"
        , "hi "//5
        , " hi "
        , "this program is pissing me off!"
        , "1 2 3 4 5 6 7 8 9"
        , "1 2 3 4 5 6 7 8 9 "
        , "1 2 3 4 5 6 7 8 9 10"//10
        , "1 2 3 4 5 6 7 8 9 10 "
        , "1 2 3 4 5 6 7 8 9 10 11"
        , "1 2 3 4 5 6 7 8 9 10 11 "
        , "1 2 3 4 5 6 7 8 9 10 11 12"
        , "1 2 3 4 5 6 7 8 9 10 11 12 "//15
    };

    ArrayList<BlogEntry> albe = new ArrayList<>();

    for (String test : testStrings) {
        albe.add(new BlogEntry("" , new Date(), test));
    }

    testStrings[0] = "<was null>";

    for (int i = 0; i < albe.size(); i++ ) {
        assert(albe.get(i).getSummary().equals(testStrings[Math.min(i,11)]));
    }

    for (BlogEntry be : albe)
    {
        System.out.println( be.getSummary() );        
    }
}

会产生这个:

<was null>



 hi
hi 
 hi 
this program is pissing me off!
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10 

另外,我不知道您从哪里导入Date,但import java.util.Date;import java.sql.Date; 都不会使您的代码无错误。我不得不注释掉你的setDate 代码。

如果您的导师允许,您当然可以尝试这些其他答案中的想法,但我认为您想知道发生了什么。

【讨论】:

    【解决方案2】:

    String.indexOf 还提供了允许从特定点搜索的重载(链接到API)。使用这种方法很简单:

    public int countWort(String in , String word){
        int count = 0;
    
        int index = in.indexOf(word);
    
        while(index != -1){
            ++count;
    
            index = in.indexOf(word , index + 1);
        }
    
        return count;
    }
    

    【讨论】:

      【解决方案3】:

      我认为我们可以通过检查字符是否为空格字符来找到前 10 个单词的索引。这是一个例子:

      public class FirstTenWords
      {
          public static void main( String[] args )
          {
              String sentence = "There are ten words in this sentence, I want them to be extracted";
              String summary = firstOf( sentence, 10 );
              System.out.println( summary );
          }
      
          public static String firstOf( String line, int limit )
          {
              boolean isWordMode = false;
              int count = 0;
              int i;
              for( i = 0; i < line.length(); i++ )
              {
                  char character = line.charAt( i );
                  if( Character.isSpaceChar( character ) )
                  {
                      if( isWordMode )
                      {
                          isWordMode = false;
                      }
                  }
                  else
                  {
                      if( !isWordMode )
                      {
                          isWordMode = true;
                          count++;
                      }
                  }
                  if( count >= limit )
                  {
                      break;
                  }
              }
              return line.substring( 0, i );
          }
      }
      

      我的笔记本电脑上的输出:

      There are ten words in this sentence, I want 
      

      【讨论】:

        【解决方案4】:

        我不确定它的效率有多高,但你能在每次索引时把字符串剪掉吗?例如:

        临时博客的内容:
        这是一个测试
        是一个测试
        测试
        测试

        摘要内容:


        一个
        测试

        public String getSummary()
        {
            String summary = "";
            int wordCount = 0;
            int last;
            //Create a copy so you don't overwrite original blog
            String tempBlog = blog;
        
            while (wordCount < 10)
            {
                //May want to check if there is actually a space to read. 
                summary += tempBlog.substring(0, tempBlog.indexOf(" ")) + " ";
                tempBlog = tempBlog.substring(tempBlog.indexOf(" ")+1);
                wordCount++;
            }
        
            return summary;
        }
        

        【讨论】:

        • 不,这既不是有效的,也不是我想要做的。我想打印前 10 个单词。
        • @goldieAnneJohnson,对不起。我有一个错字。更正后的功能有效。
        【解决方案5】:

        试试这个逻辑...

        public static void main(String[] args) throws Exception {
                public static void main(String[] args) throws Exception {
            String data = "This one sentence has exactly 10 words in it ok";
        
            int wordIndex = 0;
            int spaceIndex = 0;
            int wordCount = 0;
            while (wordCount < 1 && spaceIndex != -1) {
                spaceIndex = data.indexOf(" ", wordIndex);
                System.out.println(spaceIndex > -1 
                        ? data.substring(wordIndex, spaceIndex)
                        : data.substring(wordIndex));
        
                // The next word "should" be right after the space
                wordIndex = spaceIndex + 1;
                wordCount++;
            }
        }
        

        结果:

        This
        one
        sentence
        has
        exactly
        10
        words
        in
        it
        ok
        

        更新

        regex 不是一个选项吗?使用regex,您可以尝试以下操作:

        public static void main(String[] args) throws Exception {
            String data = "The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog";
            Matcher matcher = Pattern.compile("\\w+").matcher(data);
        
            int wordCount = 0;
            while (matcher.find() && wordCount < 10) {
                System.out.println(matcher.group());
                wordCount++;
            }
        }
        

        结果:

        The
        quick
        brown
        fox
        jumps
        over
        the
        lazy
        dog
        The
        

        正则表达式返回具有以下字符 [a-zA-Z_0-9] 的单词

        【讨论】:

        • 这与我在其他代码中发生的事情相同...如果没有空格,它会占用最后一个(第 10 个)单词并删除它。
        • @GoldieAnneJohnson 查看第一个答案的更新。正则表达式不适合您吗?
        猜你喜欢
        • 2022-01-06
        • 1970-01-01
        • 1970-01-01
        • 2012-05-06
        • 2020-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-26
        相关资源
        最近更新 更多