2009-10-29 39 views
2

在應用程序中有以下格式的字符串:Java:有沒有更簡單的方法來解析字符串中的數組元素?

String elements =「[11,john,] [23,Adam,] [88,Angie,] ...」(...表示那裏是字符串中的更多元素)

從給定的字符串,我必須爲名稱(約翰,亞當,安吉,...)名稱ID(11,23,88,...)和ArrayList創建一個ArrayList。

我創建了兩個方法:

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(字符串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); 
     } 

    } 

我希望如果有人對你能提出任何簡單的方法來從給定的線二的ArrayList 。

謝謝!

回答

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... 
} 
3

兩個ArrayLists?我認爲你需要一個List,它包含具有id和name屬性的對象類型Item。

如果您單獨解析id和name,而沒有將它們封裝到一個明顯的對象中,那麼您就沒有考慮對象。

+0

我同意,儘管這並沒有真正回答這個問題。 – 2009-10-29 10:00:03

+0

對象拒絕反模式的經典案例。 – 2009-10-29 10:01:28

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())); 
    } 
} 
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是對的,關於更好的面向對象設計。

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); 
    } 
1

我做了一個簡單一點:

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