基于逗号分割字符串并在java中查询查询字符串

时间:2013-10-21 11:07:14

标签: java string delimiter string-concatenation

我有一个字符串,其中包含以逗号分隔的值。现在根据我的需要,我必须用逗号(,)拆分字符串,并将子字符串连接到查询字符串,但我无法得到这个想法。我的代码......我需要拆分String并连接到查询..

扩展包含类似1111,2341,5028

的值
String extension = request.getParameter("extension");
System.out.println(extension);
if(extension!=""){
//here i need to concate the substring into query delimited by comma.
query=query.concat("'").concat(" and extension='"+extension);

}

任何帮助将受到高度赞赏.. 提前谢谢..

4 个答案:

答案 0 :(得分:1)

您可以使用split方法逐个获取子字符串

for (String ext: extension.split(",")){
   // your code goes here
  }

答案 1 :(得分:1)

试试这个,

{
        String myInput = "1111,2341,5028";
        String[] splitted = myInput.split(",");

        String query = " Select * from Table where "; // something like Select * from Table where 
        StringBuilder concanatedquery= new StringBuilder();

        for (String output : splitted) 
        {
            concanatedquery.append(" extension = '" + output.replace("'", "''") +"'  AND ");    //replace confirms that no failure will be there if splited string contains ' and if this splitted string are numeric then remove 'replace' clause and char ' after extension = ' and before "' AND"            
        }

        query = query + concanatedquery.substring(0, concanatedquery.length() - 4); //4 characters are removed as 'AND  ' will be extra at the end.
}

答案 2 :(得分:0)

使用StringBuilder类连接并构建SQL查询,该查询具有追加方法。

String [] parts = originalString.split(",");
StringBuilder builder = new StringBuilder();
for(String str: parts){
 builder.append(str);
builder.append(" ");
}
return builder.toString();

答案 3 :(得分:0)

你可以分割字符串像这样

String str = "1111,2341,5028";
String filenameArray[] =  str.split("\\,");
// ACCESS THE ARRAY POSITION LIKE filenameArray[0],filenameArray[1]  AND SO ON