【问题标题】:Java string.length not working as expected [closed]Java string.length 未按预期工作[关闭]
【发布时间】:2016-12-01 12:07:07
【问题描述】:

我有一个文件,其中包含一些格式的数据:

12345foo \n
24561bar \n
12783apples \n ect.

为了处理这些数据,我正在使用 bufferedreader 将其读入一个程序,并将其放入一个二维数组中,代码如下:

line = bRead.readLine();
2DArray[x][y] = line.substring(0,5);
2DArray[x][z] = line.substring(5,line.length());

我不确定为什么在这种情况下 line.length 显然给了我(line.length() - 5)

【问题讨论】:

  • 呃,不是。 line.length() 给你line.length()。你对substring的第二个参数的含义感到困惑吗? It's the offset from the start,不是5 之后的字符数。不是说你需要传递第二个参数,如果你只想要字符串的其余部分。
  • 似乎您可能会在正则表达式 \d\D 中找到用于仅获取数字和非数字的用途
  • 您的期望是什么?为什么你认为 line.length() 会给你字符串的长度减 5?
  • 您的代码将12345foo分开,代码没有问题,我认为您的看法是错误的。
  • 您要这样做吗? 2DArray[x][z] = line.substring(5);

标签: java arrays string bufferedreader


【解决方案1】:

你应该这样做:

line.substring(5);

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)

public static void main(String[] args) {

    BufferedReader bR = null;

    try {
        bR = new BufferedReader(new FileReader("teste.txt"));

        Map<String, String> txt = new HashMap<String, String>();
        String line;

        while ((line = bR.readLine()) != null) {
            txt.put(line.substring(0, 5), line.substring(5));
        }

        txt.forEach((k, v) -> System.out.println(k + " - " + v));

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bR != null) {
            try {
                bR.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Output:

24561 - bar
12345 - foo
12783 - apples

【讨论】:

    【解决方案2】:

    如果我必须批准和审查您的代码,我的第一个问题是“您为什么使用数组?”将逻辑上属于一起的数据拆分为 2D 数组或 Map,是我认为不好的代码。您显然有一个带有 id 和名称的行项目,因此您应该有这样一个对象的域模型。 这就是我要做的。

    package com.example
    
    import java.io.BufferedReader;
    import java.io.StringReader;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
    
            String data = "12345foo\n" +
                          "24561bar\n" +
                          "12783apples\n";
    
            BufferedReader br = new BufferedReader(new StringReader(data));
            String line = null;
            List<LineItem> items = new ArrayList<>();
            while (null != (line = br.readLine())) {
                int id = Integer.parseInt(line.substring(0, 5));
                String name = line.substring(5);
                items.add(new LineItem(id, name));
            }
    
            items.forEach(lineItem -> System.out.println(lineItem));
    
        }
    
        public static class LineItem {
            private final int id;
            private final String name;
    
            public LineItem(int id, String name) {
                this.id = id;
                this.name = name;
            }
    
            @Override
            public String toString() {
                return "LineItem{" +
                        "id=" + id +
                        ", name='" + name + '\'' +
                        '}';
            }
        }
    }
    

    【讨论】:

    • 代码缺少一个 try 块,但似乎我无法编辑代码 sn-p :(
    【解决方案3】:

    在 java 中,line.substring() 使用第一个参数来确定距起点的偏移量,第二个参数用于确定...距起点的偏移量。例如,

    String foo = "barAndSomeOtherStuff"; System.out.print(foo.substring (5, 12));

    将输出“dSomeOt”,而不是“dSomeOtherSt”。

    解决此类问题的一个好主意是在访问 StackOverflow 之类的地方之前查看文档!

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 2017-07-13
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多