Month: March 2014

Concenate Array String Using StringBuilder in Java

My recent project is converting a PHP application into Java. I have found this code in PHP. I think this piece of code is interesting because I have found this code a lot from the application.

Below code used for tricky query block in PHP

$nu_filters = preg_replace('/[^a-zA-Z0-9]+/', ' ', $filter);
$search_words = explode(" ", $nu_filters);
$thisWhere = "";
 foreach($search_words as $sword)
 {
     $thisWhere .= " content_all like '%".$sword."%' $operator_concat ";
 }
$thisWhere_count = strlen($thisWhere);
 //echo $thisWhere;
$where = " (".substr($thisWhere, 0, $thisWhere_count - 4).") ";
return $where;

And this is the Java code using StringBuilder:

public class TheQuery {
    public StringBuilder secondWhereLogic(String filter, String operator_concat) {

        String nu_filter = filter.replaceAll("/[^a-zA-Z0-9]+/", " ");

        String[] search_words = nu_filter.split(" ");

        StringBuilder newStr = new StringBuilder();

        for(int i = 0; i < search_words.length; i++) {
            newStr.append(" content_all like '%"+search_words[i]+"%' or ");
        }
        return newStr;
    }
}

Thats it… 🙂