【问题标题】:Parsing lists & strings解析列表和字符串
【发布时间】:2013-12-04 16:59:07
【问题描述】:

我正在使用此代码和 ds list 打印例如:

aaa.(bbb)
aaa.(eee)
ccc.(ddd) 
...

我需要它在相同的括号中打印与aaa 相关的字符串,以分隔它们。

例如:aaa.(bbb,eee)

我应该对我的代码进行哪些更改?

我知道代码不完整,但如果我添加所有内容,它会变得复杂很多。目标是在迭代字符串 s 的 templist 时,以上述格式添加 templist 元素。

List<String> templist = new ArrayList<String>() ;
List<String> ds = new ArrayList<String>() ;

String s = "aaa"

String selecfin = null ;

for(int j =0;j<templist.size(); j++){

       String selecP = templist.get(j);

       selecfin = s+".("+selecP+")";
       ds.add(selecfin);
}

【问题讨论】:

  • 根据您的代码,除了aaa.(xxx),它不能打印任何内容。 s 中的值什么时候变化?
  • 我建议您创建一个类似 Map> 的结构,将根 ("aaa", "ccc") 作为键并添加到字符串列表为价值观。

标签: java string list parsing


【解决方案1】:

我没测试过,你可以这样试试

List<String> templist = new ArrayList<String>() ;
List<String> ds = new ArrayList<String>() ;

String s = "aaa";

String selecfin = null ;
String tmp = null;

for(int i=0; i<templist.size(); i++) {
  if(tmp != null) {
    tmp = tmp + "," + templist.get(i);
  } else {
    tmp = templist.get(i);
  }
}

selecfin = s + ".(" + tmp + ")";

ds.add(selecfin);

【讨论】:

  • 请不要发布未经测试的内容。至少在 IdeOne 上运行它
【解决方案2】:

你可以检查aaa的存在,如下:

if(selecP.contains("aaa")){
  // separate and do what you need
}  

以上述格式添加临时列表元素。 我不太明白这意味着什么。

此外,您可以使用 for-each 循环使代码更紧凑,如下所示:

for(String selecP : tempList){
  if(selecP.contains("aaa"){
      // something
  }
}  

您没有在您提供的代码 sn-p 中向列表中添加任何内容。您正在遍历空列表。


SSCCE:
在这里运行它:http://ideone.com/66EIax

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        List<String> tempList = new ArrayList<String>();
        List<String> ds = new ArrayList<String>();

        tempList.add("aaa.(bbb)");
        tempList.add("aaa.(eee)");
        tempList.add("ccc.(ddd)");

        String s = "aaa";

        for(String selecP : tempList){
            if(selecP.contains(s)){
                ds.add(new String(selecP));
            }
        }

        for(String each : ds){
            System.out.println(each);
        }
    }
}  

输出:

aaa.(bbb)
aaa.(eee)

【讨论】:

  • 这个输出不是 OP 想要的;在这种情况下,所需的输出是aaa.(bbb,eee)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
相关资源
最近更新 更多