简体   繁体   English

在 Java 中删除字符串中的最后 n 行(句子)

[英]Remove last n lines (sentences) in a String in Java

I am looking for an efficient way to remove last n lines from a String.我正在寻找一种从字符串中删除最后 n 行的有效方法。 Efficient as in- fast performing as well as something that does not create too may objects.效率低,执行速度慢,并且不会创建太多对象。 Therefore would like to stay away from split().因此想远离split()。 Especially because, at times, my strings could be a few hundred or even thousand lines.特别是因为有时,我的字符串可能是几百甚至几千行。

For instance, I am getting a string as such:例如,我得到一个字符串:

This is a sample code line 1.
This is a sample code line 2.

Warm Regards,
SomeUser.

The last 3 lines (an empty line, "Warm Regards,", and "SomeUser.") is what I am trying to get rid of.最后 3 行(空行,“热情的问候”和“SomeUser。”)是我想要摆脱的。 Note that the content (including the last 3 lines) isn't fixed.请注意,内容(包括最后 3 行)不是固定的。

I am thinking of counting the lines first using this solution here: https://stackoverflow.com/a/18816371/1353174 and then again, use another similar loop to reach to a position that is lines - n and do a substring till that position.我想先在这里使用这个解决方案来计算行数: https : //stackoverflow.com/a/18816371/1353174然后再一次,使用另一个类似的循环到达一个位置,即行 - n 并做一个子串直到那个位置。

However, just posting this problem here to know if there are any other and perhaps more efficient ways to achieve this.但是,只需在此处发布此问题即可了解是否还有其他可能更有效的方法来实现此目的。 External library-based solutions (like Apache Commons StringUtils) are also welcome.也欢迎使用基于外部库的解决方案(如 Apache Commons StringUtils)。

You can use String.lastIndexOf to find last third occurrence of '\\n' symbol and then do String.substring to get the result.您可以使用String.lastIndexOf找到最后第三次出现的 '\\n' 符号,然后执行String.substring来获得结果。

     public static void main(String[] args) {
        String s = "This is a sample code line 1.\n" +
                "This is a sample code line 2.\n" +
                "\n" +
                "Warm Regards,\n" +
                "SomeUser.";

        int truncateIndex = s.length();

        for (int i = 0; i < 3; i++) {
            System.out.println(truncateIndex);
            truncateIndex = s.lastIndexOf('\n', truncateIndex - 1);
        }

        System.out.println(s.substring(0, truncateIndex));
        System.out.println("--");
    }

This code snippet intentionally doesn't care for corner cases, such as when there is less than three lines in input string, to make code simple and readable.此代码片段有意不考虑极端情况,例如输入字符串少于三行时,以使代码简单易读。

public static final String SAMPLE_TEXT = "This is a sample code line 1.\nThis is a sample code line 2.\r\n\nWarm Regards,\r\nSomeUser.";

public static void main (String[] args) throws java.lang.Exception {
    String[] lines = SAMPLE_TEXT.split("\\r?\\n"); // catches Windows newlines (\r) as well)
    for (int i = 0; i < lines.length - 3; i++) {   // lines.length - 3 to discard the last 3 lines
        System.out.println(lines[i]);
    }
}

Here's a runnable example:这是一个可运行的示例:

http://ideone.com/nwaMcD http://ideone.com/nwaMcD

  @scala.annotation.tailrec
  def rmLines(in: String, nlines: Int): String =
    if (nlines == 0) {
      in
    } else {
      val lastBreakIndex = in.lastIndexOf('\n')
      if (lastBreakIndex == -1) {
        in
      } else {
        rmLines(in.substring(0, lastBreakIndex), nlines - 1)
      }
    }

使用正则表达式来做到这一点: http : //docs.oracle.com/javase/tutorial/essential/regex/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM