Java:有没有更简单的方法来解析字符串中的数组元素?

时间:2009-10-29 09:44:49

标签: java string

在应用程序中,有一个字符串,格式如下:

String elements =“[11,john,] [23,Adam,] [88,Angie,] ......”(...表示字符串中有更多元素)

从给定的字符串中我必须为名称ID(11,23,88,...)创建一个ArrayList,为名称创建一个ArrayList(john,Adam,Angie,...)

我创建了两种方法:

private int getItemID(int listLocation, String inputString){
    int indexBeginning = inputString.indexOf("[", listLocation) + 1;
    int indexEnd = inputString.indexOf(",", listLocation) - 1;
    String sID = inputString.substring(indexBeginning, indexEnd);
    int result = Integer.parseInt(sID);
    return result;
}

private String getItemName(int listLocation, String inputString){
    int indexBeginning = inputString.indexOf(" ", listLocation) + 1;
    int indexEnd = inputString.indexOf(",", indexBeginning) - 1;
    String result = inputString.substring(indexBeginning, indexEnd);
    return result;
}

并打算在方法parseArrayString(String inputString)中使用这两个方法,我还没有写过,但是可以按以下方式工作:

private void parseCommunityList(String inputString){
        int currentLocation = 0;
        int itemsCount = count the number of "[" characters in the string
        for(int i = 0; i < itemsCount; i++)
        {
               currentLocation = get the location of the (i)th character "[" in the string;
               String name = getItemName(currentLocation, inputString);
               int ID = getItemID(currentLocation, inputString);
               nameArray.Add(name);
               idArray,Add(ID);
        }

    }

如果你们中的任何人能够提出任何更简单的方法来从给定的字符串创建两个ArrayLists,我将不胜感激。

谢谢!

6 个答案:

答案 0 :(得分:7)

我建议使用正则表达式,使用组捕获所需的元素。下面的示例创建了Person个对象的列表,而不是String个的单个列表 - 封装了其他海报建议的数据:

    List<Person> people = new ArrayList<Person>();

    String regexpStr = "(\\[([0-9]+),\\s*([0-9a-zA-Z]+),\\])";
    String inputData = "[11, john,][23, Adam,][88, Angie,]";

    Pattern regexp = Pattern.compile(regexpStr);
    Matcher matcher = regexp.matcher(inputData);
    while (matcher.find()) {
        MatchResult result = matcher.toMatchResult();

        String id = result.group(2);
        String name = result.group(3);

        Person person = new Person(Long.valueOf(id), name);
        people.add(person);
    }

一个封装数据的简单类:

public class Person {
    private Long id;
    private String name;

    public Person(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    // TODO equals, toString, hashcode...
}

答案 1 :(得分:3)

两个ArrayLists?我认为你需要一个List包含具有id和name属性的对象类型Item。

如果你单独解析id和name,而不将它们封装到一个明显的对象中,你就不会考虑对象了。

答案 2 :(得分:1)

我做了一些更简单的事情:

String str = "   [ 1 , 2 ]   ";
str = str.trim();
String[] strArgs = str.substring(1, str.length() - 1).trim().split("\\s*,\\s*");

答案 3 :(得分:0)

类似的东西:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IdNamePairs {

    private List<Integer> ids = new ArrayList<Integer>();
    private List<String> names = new ArrayList<String>();

    public IdNamePairs(String string) {
        Pattern p = Pattern.compile("\\[([^\\]]+)\\]");
        Matcher m = p.matcher(string);
        while (m.find()) {
            String tuple = m.group(1);
            String[] idName = tuple.split(",\\s*");
            ids.add(Integer.valueOf(idName[0]));
            names.add(idName[1]);
        }
    }

    public List<Integer> getIds() {
        return Collections.unmodifiableList(ids);
    }

    public List<String> getNames() {
        return Collections.unmodifiableList(names);
    }

    public static void main(String[] args) {
        String str = "[11, john,][23, Adam,][88, Angie,]";
        IdNamePairs idNamePairs = new IdNamePairs(str);
        System.out.println(Arrays.toString(idNamePairs.getIds().toArray()));
        System.out.println(Arrays.toString(idNamePairs.getNames().toArray()));
    }
}

答案 4 :(得分:0)

这是一个简化的例子:

List<String> nameArray = new ArrayList<String>();
List<String> idArray = new ArrayList<String>();
String input = "[11, john,][23, Adam,][88, Angie,]";
String[] pairs = input.split("((\\]\\[)|\\[|\\])");

for (String pair : pairs) {
    if (pair.length() > 0) {
        String[] elems = pair.split(", *");

        idArray.add(elems[0]);
        nameArray.add(elems[1]);
    }
}

System.out.println("IDs: " + idArray);
System.out.println("Names: " + nameArray);
但是,duffymo是正确的,关于更好的面向对象设计。

答案 5 :(得分:0)

包括测试! ;)

    class Entry {
        final int number;
        final String name;
        public Entry(int number, String name) {
            this.number = number;
            this.name = name;
        }
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            result = prime * result + number;
            return result;
        }
        @Override
        public String toString() {
            return "Entry [name=" + name + ", number=" + number + "]";
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Entry other = (Entry) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            if (number != other.number)
                return false;
            return true;
        }
    }

    class ElementsSplitter {

        public List<Entry> split(String elements) {
            List<Entry> entries = new ArrayList();
            Pattern p = Pattern.compile("\\[(\\d+),\\s*(\\w+),\\]");
            Matcher m = p.matcher(elements);
            while (m.find()) {
                entries.add(new Entry(Integer.parseInt(m.group(1)), m.group(2)));
            }
            return entries;
        }

    }

    @Test
    public void testElementsSplitter() throws Exception {
        String elementsString = "[11, john,][23, Adam,][88, Angie,]";
        ElementsSplitter eSplitter = new ElementsSplitter();
        List<Entry> actual = eSplitter.split(elementsString);
        List<Entry> expected = Arrays.asList(
                new Entry(11, "john"),
                new Entry(23, "Adam"),
                new Entry(88, "Angie"));
        assertEquals(3, actual.size());
        assertEquals(expected, actual);
    }