拆分并删除新行

时间:2014-07-23 07:33:03

标签: java list arraylist

我尝试用逗号分割文本并添加到每个列表中。文字样本:

  

用户1,角色1

     

用户2,角色2
  用户3,角色3

 user 4 , role 4

 user 5 , role 5

功能:

private Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
public String splitString(String sentence) {
    List<String> list;
    String[] dividedByNewLine = sentence.split("\n");
    for (int i = 0; i < dividedByNewLine.length; i++) {
            String[] divideByComma = dividedByNewLine[i].split(",");
            list = new ArrayList<String>();
            for (int j = 0; j < divideByComma.length; j++) {
                list.add(divideByComma[j].trim());
            }
            if (!list.isEmpty()) {
                map.put(i, list);
            }
            System.out.println(map.get(i));

    }

    return null;
}

但功能构建列表如下:

  

[用户1,角色1]

     

[]

     

[用户2,角色2]

     

[用户3,角色3]

     

[]

     

[用户4,角色4]

     

[]

     

[用户5,角色5]

如何删除&#34; []&#34;在列表中?

4 个答案:

答案 0 :(得分:0)

因为您的输入有空行。如果您不想显示空行,您的代码应为:

for (int i = 0; i < dividedByNewLine.length; i++) {
    if (!dividedByNewLine[i].trim().isEmpty()){
      String[] divideByComma = dividedByNewLine[i].split(",");
            list = new ArrayList<String>();
            for (int j = 0; j < divideByComma.length; j++) {
                list.add(divideByComma[j].trim());
            }
            if (!list.isEmpty()) {
                map.put(i, list);
            }
            System.out.println(map.get(i));
   }
}

答案 1 :(得分:0)

dividedByNewLine中搜索所有空行并删除它们!然后你会得到

user 1 , role 1
user 2 , role 2
user 3 , role 3
user 4 , role 4
user 5 , role 5

dividedByNewLine[i].split(",")dividedByNewLinefor (int i = 0; i < dividedByNewLine.length; i++) { if(!dividedByNewLine[i].isEmpty()) { String[] divideByComma = dividedByNewLine[i].split(","); ... } } 非空:

{{1}}

答案 2 :(得分:0)

试试这个for循环:

for (int i = 0; i < dividedByNewLine.length; i++) {
        if(!dividedByNewLine[i].trim().equals("")) {
            String[] divideByComma = dividedByNewLine[i].split(",");

        list = new ArrayList<String>();
        for (int j = 0; j < divideByComma.length; j++) {
            list.add(divideByComma[j].trim());
        }
        if (!list.isEmpty()) {
            map.put(i, list);
        }
        System.out.println(map.get(i));
        }
}

基本上,你必须跳过空行。

答案 3 :(得分:0)

您可以在添加到列表之前消除[]: -

for (int i = 0; i < dividedByNewLine.length; i++) {
        String[] divideByComma = dividedByNewLine[i].split(",");

        //Add this control statement
        if(divideByComma.isEmpty())
        continue;       //If the string is empty then continue the loop

        list = new ArrayList<String>();
        for (int j = 0; j < divideByComma.length; j++) {
            list.add(divideByComma[j].trim());
        }
        if (!list.isEmpty()) {
            map.put(i, list);
        }
        System.out.println(map.get(i));

}