1

I have .txt file, and I want to read from it to char array.

I have problem, in the .txt file I have:

1  a

3  b

2  c

which mean that a[1]='a', a[3]='b', a[2]='c'.

How in reading the file, I ignore from spaces, and consider the new lines? Thanks

4

2 回答 2

1

我建议您改用 a Map,因为它更适合此类问题。:

public static void main(String[] args) {

    Scanner s = new Scanner("1 a 3 b 2 c"); // or new File(...)

    TreeMap<Integer, Character> map = new TreeMap<Integer, Character>();

    while (s.hasNextInt())
        map.put(s.nextInt(), s.next().charAt(0));
}

如果您想将其转换TreeMapchar[]您可以执行以下操作:

char[] a = new char[map.lastKey() + 1];

for (Entry<Integer, Character> entry : map.entrySet())
    a[entry.getKey()] = entry.getValue();

笔记:

  • 此解决方案不适用于负索引
  • 如果不止一个,则只取“第一个”字符
于 2012-05-04T07:28:30.910 回答
0

使用Scanner.

ArrayList<String> a = new ArrayList<String>();
Scanner s = new Scanner(yourFile);
while(s.hasNextInt()) {
    int i = s.nextInt();
    String n = s.next();
    a.add(n);
}

当然,这大胆假设输入正确;你应该更加偏执。如果需要对每一行进行特殊处理,可以使用hasNextLine()and nextLine(),然后使用split()String 类中的分割行。

于 2012-05-04T07:29:23.700 回答