简体   繁体   English

如何在Java中拆分String []中的不同数据类型

[英]How to split different data types in String[] in Java

I would appreciate if someone could help me with my school project. 如果有人可以帮助我完成我的学校项目,我将不胜感激。 I have a txt file with names and phone numbers (ex. John Smith 1123456789). 我有一个包含名称和电话号码的txt文件(例如John Smith 1123456789)。 I need Java to read the file and load it into two separate array strings: one with first/last names and another with phone numbers. 我需要Java才能读取文件并将其加载到两个单独的数组字符串中:一个带有名字/姓氏,另一个带有电话号码。 Please give me advise on how to do it right. 请给我有关正确操作方法的建议。 Thanks a lot in advance. 非常感谢。

         String book;
         FileReader reader;
         BufferedReader buffer;
         String line;
         String[] list;

    try {
        reader = new FileReader(book);
        buffer = new BufferedReader(reader);
        list = new String[50];
        int x = 0;
        line = buffer.readLine();
        while (line != null){
            list[x] = line;
            line = buffer.readLine();
            x++;
        }
        buffer.close();
    } catch(FileNotFoundException e)

If you split the line as follows - 如果按以下方式拆分 line -

String[] fields = line.split("\\s+"); // \\s+ means one or more space(s)

the result array fields will have 3 elements - 结果数组fields将包含3个元素-

  1. first name at index 0 索引0处的名字
  2. last name at index 1 索引1的姓氏
  3. phone number at index 2 索引2的电话号码

Currently, you don't seem to have the 2 arrays for storing the names and phones. 当前,您似乎没有两个用于存储名称和电话的数组。 Create those too, and populate them after every split. 还要创建它们,并在每次拆分后填充它们。

I'm assuming that names/phone numbers on each line are in the same order. 我假设每行的姓名/电话号码顺序相同。 I'm also assuming (since this is a school project) that you know which separator is used between the names and the phone numbers. 我还假设(由于这是一个学校项目)您知道名称和电话号码之间使用了哪个分隔符。 After reading the line, you can split it by using String.split using the separator. 阅读该行之后,可以使用分隔符使用String.split进行拆分。 The two resulting parts will be the name and phone number, like this: 得到的两个部分将是名称和电话号码,如下所示:

line = buffer.readLine();
String[] parts = line.split("\t"); // if tab is used as the separator
String name = parts[0];
String phoneNumber = parts[1];

The approach is to create two ArrayList , split the line using String.split() and then insert them in the Lists. 方法是创建两个ArrayList ,使用String.split()拆分行,然后将其插入Lists中。

List<String> names = new ArrayList<>();
List<String> phoneNumbers = new ArrayList<>();
while (line != null){
    String[] lineArray = line.split(" ");
    names.add(lineArray[0]);
    phoneNumbers.add(lineArray[1]);
}
String[] namesArray = (String[]) names.toArray();
String[] phoneNumberArray = (String[]) phoneNumbers.toArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM