【问题标题】:splitting the comma separated string and adding it into the list [duplicate]拆分逗号分隔的字符串并将其添加到列表中[重复]
【发布时间】:2015-11-22 18:45:53
【问题描述】:

我有以下将返回字符串的方法。

  private String getExpectedList() {
        return expectedSList;
    }

所以我将它存储在字符串中,如下所示

String t = this.getExpectedList();

调试后发现字符串中的方法就像逗号分隔,如下所示

System.out.println(t);
  bonrs01721.am.grp.net:17202,bonrs01422.am.grp.net:17203,bonrs01622.am.grp.net:17204

我正在考虑设计一种方法,该方法将获取字符串,然后拆分它们中的每一个,最后将其添加到列表中,列表将是字符串类型,因此最终返回类型为列表的方法

所以我设计了一个列表

  List<String> holdvalues = new List<String>();

我该如何设计上面提到的这种方法

【问题讨论】:

  • 到目前为止,您在逗号分隔字符串方面做了哪些努力?
  • 使用youtString.split(",")

标签: java


【解决方案1】:

试试:

 List<String> holdvalues = new ArrayList<>();
 holdvalues.addAll( Arrays.asList(t.split(",")));
 System.out.println(holdvalues);

【讨论】:

  • 为什么需要一个新的 ArrayList?
【解决方案2】:

你可以这样做:

public List<String> method(String s){

    // create a list

    List <String>myList=new ArrayList<String>();
    String[] array;

    // split the string and store it in the array

    array=s.split("[,]");
    for(int i=0;i<array.length;i++){

        // store the strings in the list

        myList.add(array[i]);
    }

    //return the list

    return myList;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 2018-07-29
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多