java - 每行拆分未知数量的字符串

时间:2017-09-13 06:32:34

标签: java string split

我有一个像这样结构的文本文件:

    class Object0 extends Object1
    class Object2 extends Object3
    class Object1
    class Object4 extends Object1
    class Object3

我想拆分每个字符串并存储它。我知道如何在每行知道字符串数量时这样做,但在这种情况下,给定行上可以有两个或四个字。

这是我知道字符串数量时分割的内容:

public static void main(String[] args) {

        try {
            File f = new File("test.txt");
            Scanner sc = new Scanner(f);
            while(sc.hasNextLine()){
                String line = sc.nextLine();
                String[] details = line.split(" ");
                String classIdentifier = details[0];
                String classNameFirst = details[1];
             // String classExtends = details[2];
             // String classNameSecond = details[3];
            }
        } catch (FileNotFoundException e) {         
            e.printStackTrace();
        }

2 个答案:

答案 0 :(得分:1)

您可以在details数组上循环以获取每个分割的字符串,无论它们有多少。另外,我在您的main方法中进行了一些更改,以使其更正确(添加了一个finally子句来关闭Scanner资源)。

public static void main(String[] args) {

    Scanner sc = null;
    try {
        File f = new File("test.txt");
        sc = new Scanner(f);
        while(sc.hasNextLine()){
            String line = sc.nextLine();
            String[] details = line.split(" ");
            for(String str: details) {
                //variable str contains each value of the string split
                System.out.println(str);
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        sc.close();
    }
}

答案 1 :(得分:0)

在每次迭代中,您都可以检查是否还有两个单词:

public static void main(String[] args) {

    try {
        File f = new File("test.txt");
        Scanner sc = new Scanner(f);
        while(sc.hasNextLine()){
            String line = sc.nextLine();
            String[] details = line.split(" ");
            String classIdentifier = details[0];
            String classNameFirst = details[1];
            // this can be done because you declared there
            // can be only 2 or 4 words per line
            if (details.length==4) {
                String classExtends = details[2];
                String classNameSecond = details[3];
            }
            // do something useful here with extracted fields (store?)
            // before they get destroyed in the next iteration
        }
    } catch (FileNotFoundException e) {         
        e.printStackTrace();
    }
}