【问题标题】:Trim text file to first column with java使用java将文本文件修剪到第一列
【发布时间】:2013-04-07 17:59:14
【问题描述】:

嗯,我有这个 IP 列表。

193.137.150.5              368 ms                DANIEL-PC             
193.137.150.7              95 ms                 N/A                   
193.137.150.13             37 ms                 N/A                   
193.137.150.17             33 ms                 N/A                   
193.137.150.24             238 ms                N/A                   
193.137.150.38             74 ms                 DUARTE-PC             
193.137.150.41             26 ms                 N/A                   
193.137.150.52             176 ms                N/A   

我想使用 java 从列表中只删除 IP。

这是我的代码:

import java.io.*;
import java.util.*;

class trim{

    public static void main(String[] args) throws Exception{
        String s;
        char c;
        int i = 0;
        Scanner in = new Scanner(System.in);

        while (in.hasNextLine()){
            s = in.nextLine();
            c = s.charAt(i);
            while (c != ' '){
                System.out.print(c);
                i++;
                c = s.charAt(i);
            }
            System.out.println();
        }
    }
}

我做错了什么?

【问题讨论】:

  • 你得到什么输出?

标签: java string char substring trim


【解决方案1】:

在您的循环中,您永远不会将i 归零。这意味着您的偏移量对于第一行之后的每一行都是错误的。

    while (in.hasNextLine()){
        s = in.nextLine();
        c = s.charAt(i);
        while (c != ' '){
            System.out.print(c);
            i++;
            c = s.charAt(i);
        }
        System.out.println();
        i = 0; // Finished with this line
    }

【讨论】:

  • 非常感谢。我实际上记得这样做并且完全忘记了它之间的某个地方。
【解决方案2】:
while (in.hasNextLine()){
    s = in.nextLine();
    String[] arr = s.split(" "); // if delimeter is whitespace use s.split("\\s+")  
    System.out.println(arr[0]);
}

【讨论】:

    【解决方案3】:

    您可以简单地将字符串拆分一次并打印第二部分

    while (in.hasNextLine()){
        s = in.nextLine();
        System.out.println(s.split(" ", 1)[1]);
    }
    

    【讨论】:

      【解决方案4】:

      你没有重新初始化 i,

          while (in.hasNextLine()){
              s = in.nextLine();
              // reset i so you start reading at line begin
              i = 0;
              c = s.charAt(i);
              while (c != ' '){
                  System.out.print(c);
                  i++;
                  c = s.charAt(i);
              }
              System.out.println();
          }
      

      话虽如此,还有更简单的方法,例如使用String.split()

      【讨论】:

        【解决方案5】:

        您需要重新初始化 i = 0。 你可以在 nextLine 调用之后进行操作

            s = in.nextLine();
            i = 0;  
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-03-15
          • 2011-08-22
          • 2011-10-06
          • 1970-01-01
          • 2023-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多