简体   繁体   中英

Split String based on comma and concate into query String in java

I have a String which contains values separated by comma .Now as per my need i have to split the String by comma (,) and concatenate the Substring into query string but i am not able to get the idea ..here is my code...I need to split the String and concatenate into the query..

Extension contains the values like 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);

}

Any help will be highly appreciated.. Thanks in advance..

You can use split method and get the substrings one by one

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

Try this,

{
        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.
}

Use StringBuilder class to concatenate and build the SQL query, which has append method.

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

You could Split the string Like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM