三行代码  ›  专栏  ›  技术社区  ›  Micah Cave

如何使用扫描仪在文本文件中切换行的位置及其后的行?

  •  0
  • Micah Cave  · 技术社区  · 1 月前

    所以,如果我在txt文件中有4行,我怎么能把所有偶数行(2和4)转换成奇数行呢?

    Twas brillig and the slithy toves
    did gyre and gimble in the wabe.
    All mimsey were the borogroves,
    and the mome raths outgrabe.
    

    did gyre and gimble in the wabe.
    Twas brillig and the slithy toves
    and the mome raths outgrabe.
    All mimsey were the borogroves,
    

    到目前为止,我得到的是:

        public static void flipLines(Scanner console) {
        String text = console.nextLine();
            while (console.hasNextLine()) {
                
            }
    }
    

    对不起,不是很多,但我不知道该怎么办。有没有办法为每一行创建一个索引,这样我就可以按顺序调用它们,比如2、1、4、3或。。。?

    1 回复  |  直到 1 月前
        1
  •  1
  •   Emad Ali    1 月前

    String 按照您想要的顺序,先放第二行,然后再放第一行:

    public static void flipLines(Scanner console) {
        String text = "";
        while (console.hasNextLine()) {
            String first = console.nextLine(); // getting first line
            if (!console.hasNextLine()) { // this is incase we have odd number of lines, we don't want to have an error.
                text += first;
                break;
            }
            String second = console.nextLine();
            text += second + "\n" + first;
    
            if (console.hasNextLine()) { // this will make sure there are no extra empty lines if this was the last line.
                text += "\n";
            }
        }
    
    
        System.out.println(text);
    }
    

    但更好的方法是使用 StringBuilder ,最好用在大量添加和更改字符串的循环中,这有助于提高性能和内存。字符串每次添加内容时,计算机都会创建新的字符串 一串 字符串拼接 保持不变

        public static void flipLines(Scanner console) {
        StringBuilder text = new StringBuilder();
        while (console.hasNextLine()) {
            String first = console.nextLine();
            if (!console.hasNextLine()) {
                text.append(first);
                break;
            }
            String second = console.nextLine();
            text.append(second).append("\n").append(first);
    
            if (console.hasNextLine()) {
                text.append("\n");
            }
        }
    
    
        System.out.println(text.toString());
    }