【问题标题】:Removing a sentence from a paragraph从段落中删除一个句子
【发布时间】:2014-11-10 20:26:29
【问题描述】:

我正在尝试编写代码以从段落中删除整个句子。不管是哪个句子,但至少要有一个。

    String edit = "The cow goes moo. The cow goes boo. The cow goes roo. The cow goes jew.";
    int sentencestart = (edit.substring(edit.length()/2).indexOf('.') + edit.length()/2);
    int sentenceend = edit.substring(sentencestart).indexOf('.') + sentencestart;
    edit = edit.substring(0, sentencestart) + edit.substring(sentenceend);
    System.out.println(edit);

这是我目前拥有的代码。它目前正在打印与我开始时完全相同的字符串。有人有什么想法吗?

编辑:我错误地暗示应该删除任何句子。我的意思是除了第一句话之外的任何句子。最好将要删除的句子放在字符串中间的某个位置,而实际应用程序将用于非常大的字符串。

【问题讨论】:

  • 删除每个字符,直到达到.
  • 通过查看值来调试它以了解发生了什么,打印出 sentancestart 和 sentanceend 以查看它们是否不同。看起来他们正在评估相同的值。

标签: java string substring text-segmentation


【解决方案1】:

只需要机会句子end to int sentenceend = edit.substring(sentencestart+1).indexOf('.') + sentencestart;

我以为我试过了,但显然没有

【讨论】:

    【解决方案2】:

    用'.'分割输入特点。然后循环遍历片段,将它们全部添加回去,但跳过第二句。

    类似这样的:

      public static void main(String args[]) {
        String paragraph = "Hello. This is a paragraph. Foo bar. Bar foo.";
        String result = "";
        int i = 0;
        for (String s : paragraph.split("\\.")) {
          if (i++ == 1) continue;
          result += s+".";
        }
        System.out.println(result);
      }
    

    结果:

    Hello. Foo bar. Bar foo.
    

    【讨论】:

    • 我试过了,但不知何故它破坏了最终产品的格式。一定是我做的不对,呵呵
    • 您可能遇到了 split(".") 的问题。句点是一个正则表达式字符并且 split 接受正则表达式 - 所以用 \\. 转义句点
    【解决方案3】:

    为什么不直接按. 拆分,然后得到所需的行,例如

    string edit = "The cow goes moo. The cow goes boo. The cow goes roo. The cow goes jew.";
    return edit.Substring(edit.Split('.')[0].Length + 1,edit.Length - edit.Split('.')[0].Length - 1);
    

    输出:The cow goes boo. The cow goes roo. The cow goes jew.

    免责声明:以上代码采用C# 语法,而不是Java,但希望在Java 中也能做到这一点,只需稍作修改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      相关资源
      最近更新 更多