【问题标题】:Delimiter with space and read space after delimitor带空格的分隔符和分隔符后的读取空间
【发布时间】:2013-02-06 11:20:53
【问题描述】:

如何在分隔符 (" ") 后将空格作为字符串,因为只读取他们的名字。

public class readfile {

    public static void main(String[] args) throws IOException {

        String readFile = "";
        int i;

        if (args.length == 1) {
            readFile = args[0];

            BufferedReader reader = new BufferedReader(new FileReader(readFile));
            List<String> read = new ArrayList<String>();
            String rLine;
            while ((rLine = reader.readLine()) != null) {
                String[] items = rLine.split(" ");

                if (items[0].equals("Name")) {
                    for (i = 1; i < items.length; i++) {

                        String name = items[1];

                    }

                    System.out.println("Name is " + items[1]);
                }
            }
        }

    }
}


Classlist.txt

Name Alice Mark
Name Rebecca Appel
Name Jonah BullLock Jacob
Name Daniel Ethan Aron

输出:

名字是爱丽丝 名字是丽贝卡 名字是约拿 名字叫丹尼尔

【问题讨论】:

  • 你想达到什么输出?

标签: java delimiter


【解决方案1】:

更改以下行:

                       for (i = 1; i < items.length; i++) {

                            String name = items[1];

                        }

到:

                  String name = "";
                  for (i = 1; i < items.length; i++) {

                        name += items[i];

                    }

【讨论】:

  • 我试过了,但它变成了 Name is AliceMark Name is AliceMarkRebeccaAppel Name is AliceMarkRebeccaAppelJonahBullLockJacob Name is AliceMarkRebeccaAppelJonahBullLockJacobDanielEthanAron
【解决方案2】:

如果包含名称的文件的格式始终相同,即以“名称”开头并且名称部分之间恰好有一个空格,则可以改用以下代码:

while ((rLine = reader.readLine()) != null) {
    if (rLine.startsWith("Name ")) {
        String name = rLine.substring(5);
        System.out.println("Name is " + name);
    }
}

然后输出是例如'Name is Jonah BullLock Jacob' 第三行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2017-12-25
    相关资源
    最近更新 更多