如何从ArrayList创建完整的字符串

时间:2012-10-20 18:32:10

标签: string loops for-loop arraylist

我想从String创建ArrayList。目前,我只能从ArrayList返回最后一个值。我的代码:

eachstep = new ArrayList<String>();
for (int i = 0; i < parsedsteps.size(); i++) {
eachstep.add(parsedsteps.get(i).replaceAll("<[^>]*>", ""));
}                   
for (int i = 0; i < eachstep.size(); i++) {
    String directions = i + "."+" "+eachstep.get(i)+"\n"+;
} 

给我:

3.  This is step 3.

而不是:

1. This is step 1.          
2. This is step 2.
3. This is step 3.

如何使for循环创建String,其中包含ArrayList的所有值?

3 个答案:

答案 0 :(得分:2)

你需要在循环之外声明你的字符串,我建议使用StringBuilder,这样可以更有效地构建这样的字符串。

StringBuilder directions = new StringBuilder();
for( int i = 0; i < eachstep.size(); i++ )
{
    directions.append( i + "." + " " + eachstep.get( i ) + "\n" );
}

然后,当你想从StringBuilder中获取字符串时,只需调用directions.toString()

答案 1 :(得分:0)

String directions = "";
for (int i = 0; i < eachstep.size(); i++) {
    directions += i + "."+" "+eachstep.get(i)+"\n";
} 

答案 2 :(得分:0)

试试这个

   eachstep = new ArrayList<String>();
   for (int i = 0; i < parsedsteps.size(); i++) {
       eachstep.add(parsedsteps.get(i).replaceAll("<[^>]*>", ""));
   }
   String directions="";
   for (int i = 0; i < eachstep.size(); i++) {
       directions += i + "."+" "+eachstep.get(i)+"\n"+;
   } 

如果您有大字符串数组,您可能需要考虑使用StringBuilder,例如

  StringBuilder builder = new StringBuilder();
  for(String str: eachstep ){
       builder.append(i).append(".").append(str).append("\n");
  }
  String direction = builder.toString();