I have a string like:
String message = "This is a message for {ID_PW}. Your result is {exam_result}. Please quote {ID_PW} if replying";
I am importing data from CSV that I would like to use to replace the items between curly braces.
// Using OpenCSV to read in CSV...code omitted for brevity
values = (Map<String, String>) reader.readMap();
// values has 'ID_PW', 'exam_result', etc keys
How can I replace the items in curly braces in the message with the equivalent value of the key in values?
Probably you are looking for:
String s = "I bought {0,number,integer} mangos. From {1}, the fruit seller. Out of them {2,number,percent} were bad.";
MessageFormat formatter = new MessageFormat(s);
Object[] argz = {22, "John", 0.3};
System.out.println(formatter.format(argz));
This outputs:
I bought 22 mangos. From John, the fruit seller. Out of them 30% were bad.
Refer https://docs.oracle.com/javase/8/docs/api/java/text/MessageFormat.html for more details.
String message = "This is a message for {ID_PW}. Your result is {exam_result}. Please quote {ID_PW} if replying";
LinkedHashSet<String> fields = new LinkedHashSet<>(); // 'Automatically' handle duplicates
Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(message);
// Find 'fields' in the message that are wrapped in curly braces and add to hash set
while (m.find()) {
fields.add((m.group(1)));
}
// Go through CSV and parse the message with the associated fields
while (((values = (Map<String, String>) reader.readMap())) != null)
{
Iterator itr = fields.iterator();
String newMsg = message;
while (itr.hasNext()) {
String field = (String) itr.next();
String value = values.get(field);
if(value != null) {
newMsg = newMsg.replaceAll("\\{" + field + "\\}", value);
}
}
}
Use StringBuilder. StringBuilder is explicitly designed to be a mutable type of String. Next, don't use regular expressions in a loop. Regular expressions can be powerful, but since you will be using a loop to search for multiple patterns there is nothing regular involved (multiple patterns means multiple expressions).
I would just search left to right for { and then } extract the key and search for it in the values map. Something like,
Map<String, String> values = new HashMap<>();
values.put("ID_PW", "SimpleOne");
values.put("exam_result", "84");
String message = "This is a message for {ID_PW}. Your result "
+ "is {exam_result}. Please quote {ID_PW} if replying";
StringBuilder sb = new StringBuilder(message);
int p = -1;
while ((p = sb.indexOf("{", p + 1)) > -1) {
int e = sb.indexOf("}", p + 1);
if (e > -1) {
String key = sb.substring(p + 1, e);
if (values.containsKey(key)) {
sb.replace(p, p + key.length() + 2, values.get(key));
}
}
}
System.out.println(sb);
Outputs
This is a message for SimpleOne. Your result is 84. Please quote SimpleOne if replying
Related
I've posted about letters earlier, but this is an another topic, I have a json response that contain 2 objects, from and to , from is what to change, and to is what it will be changed to .
My code is :
// for example, the EnteredText is "ab b test a b" .
EnteredString = EnteredText.getText().toString();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String Original = jo_inside.getString("from");
String To = jo_inside.getString("to");
if(isMethodConvertingIn){
EnteredString = EnteredString.replace(" ","_");
EnteredString = EnteredString.replace(Original,To + " ");
} else {
EnteredString = EnteredString.replace("_"," ");
EnteredString = EnteredString.replace(To + " ", Original);
}
}
LoadingProgress.setVisibility(View.GONE);
SetResultText(EnteredString);
ShowResultCardView();
For example, the json response is :
{
"Response":[
{"from":"a","to":"bhduh"},{"from":"b","to":"eieja"},{"from":"tes","to":"neesj"}
]
}
String.replace() method won't work here, because first it will replace a to bhduh, then b to eieja, BUT here's the problem, it will convert b in bhduh to eieja, which i don't want to.
I want to perfectly convert the letters and "words" in the String according the Json, but that what i'm failing at .
New Code :
if(m_jArry.length() > 0){
HashMap<String, String> m_li;
EnteredString = EnteredText.getText().toString();
Log.i("TestAf_","Before Converting: " + EnteredString);
HashMap<String,String> replacements = new HashMap<String,String>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String Original = jo_inside.getString("from");
String To = jo_inside.getString("to");
if(isMethodConvertingIn){
//EnteredString = EnteredString.replace(" ","_");
replacements.put(Original,To);
Log.i("TestAf_","From: " + Original + " - To: " + To + " - Loop: " + i);
//EnteredString = EnteredString.replace(" ","_");
//EnteredString = EnteredString.replace(Original,To + " ");
} else {
EnteredString = EnteredString.replace("_"," ");
EnteredString = EnteredString.replace("'" + To + "'", Original);
}
}
Log.i("TestAf_","After Converting: " + replaceTokens(EnteredString,replacements));
// Replace Logic Here
// When Finish, Do :
LoadingProgress.setVisibility(View.GONE);
SetResultText(replaceTokens(EnteredString,replacements));
ShowResultCardView();
Output :
10-10 19:51:19.757 12113-12113/? I/TestAf_: Before Converting: ab a ba
10-10 19:51:19.757 12113-12113/? I/TestAf_: From: a - To: bhduh - Loop: 0
10-10 19:51:19.757 12113-12113/? I/TestAf_: From: b - To: eieja - Loop: 1
10-10 19:51:19.757 12113-12113/? I/TestAf_: From: o - To: neesj - Loop: 2
10-10 19:51:19.758 12113-12113/? I/TestAf_: After Converting: ab a ba
You question would be clearer if you gave the expected output for the function.
Assuming it is: ab b test a b >>>> bhduheieja eieja neesjt bhduh eieja
then see the following, the key point in the Javadoc being "This will not repeat"
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#replaceEach(java.lang.String,%20java.lang.String[],%20java.lang.String[])
Replaces all occurrences of Strings within another String.
A null reference passed to this method is a no-op, or if any "search
string" or "string to replace" is null, that replace will be ignored.
This will not repeat. For repeating replaces, call the overloaded
method.
Example 1
import org.apache.commons.lang3.StringUtils;
public class StringReplacer {
public static void main(String[] args) {
String input = "ab b test a b";
String output = StringUtils.replaceEach(input, new String[] { "a", "b", "tes" },
new String[] { "bhduh", "eieja", "neesj" });
System.out.println(input + " >>>> " + output);
}
}
Example 2
import org.apache.commons.lang3.StringUtils;
public class StringReplacer {
public static void main(String[] args) {
String input = "this is a test string with foo";
String output = StringUtils.replaceEach(input, new String[] { "a", "foo" },
new String[] { "foo", "bar"});
System.out.println(input + " >>>> " + output);
}
}
Try following:
Solution 1:
Traverse the String characters one by one and move the new String to a new StringBuffer or StringBuilder, then call toString() to get the result. This will need you to implement string matching algorithm.
Solution 2 (Using Regex):
For this, you must know the domain of your string. For example, it is [a-zA-Z] then other arbitrary characters (not part of domain) can be used for intermediate step. First replace the actual characters with arbitrary one then arbitrary ones with the target. In example below, [!##] are the arbitrary characters. These can be any random \uxxxx value as well.
String input = "a-b-c";
String output = input.replaceAll("[a]", "!").replaceAll("[b]", "#").replaceAll("[c]", "#");
output = output.replaceAll("[!]", "bcd").replaceAll("[#]", "cde").replaceAll("[#]", "def");
System.out.println("input: " + input);
System.out.println("Expected: bcd-cde-def");
System.out.println("Actual: " + output);
Your issue is quite common. To sum things up :
String test = "this is a test string with foo";
System.out.println(test.replace("a", "foo").replace("foo", "bar"));
Gives : this is bar test string with bar
Expected by you : this is foo test string with bar
You can use StrSubstitutor from Apache Commons Lang
But first you will have to inject placeholders in your string :
String test = "this is a test string with foo";
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("a", "foo");
valuesMap.put("foo", "bar");
String testWithPlaceholder = test;
// Preparing the placeholders
for (String value : valuesMap.keySet())
{
testWithPlaceholder = testWithPlaceholder.replace(value, "${"+value+"}");
}
And then, use StrSubstitutor
System.out.println(StrSubstitutor.replace(testWithPlaceholder, valuesMap));
It gives : this is foo test string with bar
Here is an method which is strictly just Java. I tried not to use any Java 8 methods here.
public static String translate(final String str, List<String> from, List<String> to, int index) {
StringBuilder components = new StringBuilder();
String token, replace;
int p;
if (index < from.size()) {
token = from.get(index);
replace = to.get(index);
p = 0;
for (int i = str.indexOf(token, p); i != -1; i = str.indexOf(token, p)) {
if (i != p) {
components.append(translate(str.substring(p, i), from, to, index + 1));
}
components.append(replace);
p = i + token.length();
}
return components.append(translate(str.substring(p), from, to, index + 1)).toString();
}
return str;
}
public static String translate(final String str, List<String> from, List<String> to) {
if (null == str) {
return null;
}
return translate(str, from, to, 0);
}
Sample test program
public static void main(String []args) {
String EnteredString = "aa hjkyu batesh a";
List<String> from = new ArrayList<>(Arrays.asList("a", "b", "tes"));
List<String> to = new ArrayList<>(Arrays.asList("bhduh", "eieja", "neesj"));
System.out.println(translate(EnteredString, from, to));
}
Output:
bhduhbhduh hjkyu eiejabhduhneesjh bhduh
Explaination
The algorithm is recursive, and it simply does the following
If a pattern found in the string matches a pattern in the from list
if there is any string before that pattern, apply the algorithm to that string
replace the found pattern with the corresponding pattern in the to list
append the replacement to the new string
discard the pattern in the from list and repeat the algorithm for the rest of the string
Otherwise append the rest of the string to the new string
You could use split like:
String[] pieces = jsonResponse.split("},{");
then you just parse the from and to in each piece and apply them with replace() then put the string back together again. (and please get your capitalization of your variables/methods right - makes it very hard to read the way you have it)
Apache Commons StringUtils::replaceEach does this.
String[] froms = new String[] {"a", "b"};
String[] tos = new String[] {"b","c"};
String result = StringUtils.replaceEach("ab", froms, tos);
// result is "bc"
Why not keep it very simple (if the JSON is always in same format, EG: from the same system). Instead of replacing from with to, replace the entire markup:
replace "from":"*from*" with "from":"*to*"
Why not just change the actual "to" and "from" labels? That way, you don't run into a situation where "bhudh" becomes "eieja". Just do a string replace on "from" and "to".
I am new in java I want to chunk string which is present in arraylist.
For Example : My String ="I am going to Department of agriculture science near to my house" then i want to chunk Department-of-agriculture-science which i added in arraylist in my code
Another Example like "You can use either Iterator or ListIterator for traversing on Java ArrayList" From my code it will give problem something is wrong. but i want output as "You can use either Iterator or ListIterator-for-traversing-on-Java-ArrayList. "ListIterator for traversing" and "traversing on Java ArrayList" is already in arraylist.
I want to chunk token only which i added in list like "Department of ayurveda" "ListIterator for traversing". if my string is "You can use either Iterator or ListIterator for traversing on Java ArrayList" then output should be "You can use either Iterator or ListIterator-for-traversing-on-Java-ArrayList"
My Code :
String input = "You can use either Iterator or ListIterator for traversing on Java ArrayList";
ArrayList<String> alPatterns = new ArrayList<String>();
alPatterns.add("Department of ayurveda");
alPatterns.add("science");
alPatterns.add("ListIterator for traversing");
alPatterns.add("for traversing on Java ArrayList");
int NoOfRecords = alPatterns.size();
int counter = 0;
final int flags = Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE;
Iterator it = alPatterns.iterator();
while (counter++ < NoOfRecords) {
try {
String sPat = (String) it.next();
Pattern p = Pattern.compile(sPat, flags);
Matcher m = p.matcher(input);
OUTER: while (m.find()) {
String sMatchFound = m.group();
String newstring = sMatchFound.replaceAll(" ", "-");
input = input.replaceAll(sMatchFound, newstring);
continue OUTER;
}
System.out.println(input);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have to count the occurrences of each String in an ArrayList that includes Strings and ints. Right now I have to ignore the int variable that corresponds to the quantity of every item and just count the repetitions of each String in that list.
My problem is that in class we only did this with ints. Now with Strings I'm having a problem with the casing because "abc" is different than "Abc" and "def of Ghi" is different from "Def of ghi".
Right now the code I have is this:
Map<String, Integer> getCount1 = new HashMap<>();
{
for (ItemsList i : list) {
Integer count = getCount1.get(i.name);
if (count == null) {
count = 0;
}
getCount1.put(i.name, (count.intValue() + 1));
}
for (Map.Entry<String, Integer> entry : getCount1.entrySet())
f.println(entry.getKey() + " : " + entry.getValue());
}
But as I said: it is not counting the occurrences correctly. I have, for example, one occurrence in my list called "Abc of abc" then in the input.txt file list I have that same occurrence 4 times - "Abc of abc"; "abc of Abc"; "Abc of Abc" and "abc Of abc" - all written differently and it's counting them separately instead of the same occurrence 4 times.
Early on when I was working on the totals and averages I was able to use equalsIgnoreCase() so it works fine in there, so regardless of the casing, it's counting them in the right list but not as just one occurrence several times.
Is there a way that I could use the ignore case or convert everything to the same case before counting them?
Just an update: Instead of trying the .toLowerCase() there I used it in the FileReader when it reads the .txt file and it worked i.name = name.toLowerCase();
Thanks for your time and help anyway
Try this :
public void getCount(){
Map<String, Integer> countMap = new HashMap<String, Integer>();
for(ItemsList i : itemsList){
if(countMap.containsKey(i.Name.toLowerCase())){
countMap.get(i.Name.toLowerCase())++;
}
else{
countMap.put(i.Name.toLowerCase(),1);
}
}
}
The hashing function for a HashMap is case sensitive, so you need to uppercase or lowercase the string values. See below your modified code:
Map<String, Integer> getCount1 = new HashMap<>();
{
for (ItemsList i : list) {
Integer count = getCount1.get(i.name);
if (count == null) {
count = 0;
}
getCount1.put(i.name.toString(). toLowerCase() , (count.intValue() + 1));
}
for (Map.Entry<String, Integer> entry : getCount1.entrySet())
f.println(entry.getKey() + " : " + entry.getValue());
}
As a point of style I'd use a more descriptive name for the items in your ItemsList like item.
Instead of trying the .toLowerCase() there I used it in the FileReader when it reads the .txt file and it worked i.name = name.toLowerCase();
So in the end my code there was this:
static void readFile(ArrayList<Items> list) throws IOException {
BufferedReader in = new BufferedReader(
new FileReader("input.txt")
);
String text;
while( (text = in.readLine()) != null ) {
if(text.length()==0) break;
Scanner line = new Scanner(text);
linha.useDelimiter("\\s*:\\s*");
String name = line.next();
int qtt = line.nextInt();
Items i = new Items();
i.name = name.toLowerCase();
i.qtt = qtt;
list.add(i);
}
in.close();
}
I try to split a String into tokens.
The token delimiters are not single characters, some delimiters are included into others (example, & and &&), and I need to have the delimiters returned as token.
StringTokenizer is not able to deal with multiple characters delimiters. I presume it's possible with String.split, but fail to guess the magical regular expression that will suits my needs.
Any idea ?
Example:
Token delimiters: "&", "&&", "=", "=>", " "
String to tokenize: a & b&&c=>d
Expected result: an string array containing "a", " ", "&", " ", "b", "&&", "c", "=>", "d"
--- Edit ---
Thanks to all for your help, Dasblinkenlight gives me the solution. Here is the "ready to use" code I wrote with his help:
private static String[] wonderfulTokenizer(String string, String[] delimiters) {
// First, create a regular expression that matches the union of the delimiters
// Be aware that, in case of delimiters containing others (example && and &),
// the longer may be before the shorter (&& should be before &) or the regexpr
// parser will recognize && as two &.
Arrays.sort(delimiters, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return -o1.compareTo(o2);
}
});
// Build a string that will contain the regular expression
StringBuilder regexpr = new StringBuilder();
regexpr.append('(');
for (String delim : delimiters) { // For each delimiter
if (regexpr.length() != 1) regexpr.append('|'); // Add union separator if needed
for (int i = 0; i < delim.length(); i++) {
// Add an escape character if the character is a regexp reserved char
regexpr.append('\\');
regexpr.append(delim.charAt(i));
}
}
regexpr.append(')'); // Close the union
Pattern p = Pattern.compile(regexpr.toString());
// Now, search for the tokens
List<String> res = new ArrayList<String>();
Matcher m = p.matcher(string);
int pos = 0;
while (m.find()) { // While there's a delimiter in the string
if (pos != m.start()) {
// If there's something between the current and the previous delimiter
// Add it to the tokens list
res.add(string.substring(pos, m.start()));
}
res.add(m.group()); // add the delimiter
pos = m.end(); // Remember end of delimiter
}
if (pos != string.length()) {
// If it remains some characters in the string after last delimiter
// Add this to the token list
res.add(string.substring(pos));
}
// Return the result
return res.toArray(new String[res.size()]);
}
It could be optimize if you have many strings to tokenize by creating the Pattern only one time.
You can use the Pattern and a simple loop to achieve the results that you are looking for:
List<String> res = new ArrayList<String>();
Pattern p = Pattern.compile("([&]{1,2}|=>?| +)");
String s = "s=a&=>b";
Matcher m = p.matcher(s);
int pos = 0;
while (m.find()) {
if (pos != m.start()) {
res.add(s.substring(pos, m.start()));
}
res.add(m.group());
pos = m.end();
}
if (pos != s.length()) {
res.add(s.substring(pos));
}
for (String t : res) {
System.out.println("'"+t+"'");
}
This produces the result below:
's'
'='
'a'
'&'
'=>'
'b'
Split won't do it for you as it removed the delimeter. You probably need to tokenize the string on your own (i.e. a for-loop) or use a framework like
http://www.antlr.org/
Try this:
String test = "a & b&&c=>d=A";
String regEx = "(&[&]?|=[>]?)";
String[] res = test.split(regEx);
for(String s : res){
System.out.println("Token: "+s);
}
I added the '=A' at the end to show that that is also parsed.
As mentioned in another answer, if you need the atypical behaviour of keeping the delimiters in the result, you will probably need to create you parser yourself....but in that case you really have to think about what a "delimiter" is in your code.
I often use this piece of code in PHP
$ordine['address'] = implode(', ', array_filter(array($cliente['cap'], $cliente['citta'], $cliente['provincia'])));
It clears empty strings and join them with a ",". If only one remains it doesn't add an extra unneeded comma. It doesn't add a comma at the end. If none remains it returns empty string.
Thus I can get one of the following results
""
"Street abc 14"
"Street abc 14, 00168"
"Street abc 14, 00168, Rome"
What is the best Java implementation (less code) in Java without having to add external libraries (designing for Android)?
Updated version using Java 8 (original at the end of post)
If you don't need to filter any elements you can use
String.join(CharSequence delimiter, CharSequence... elements)
String.join(" > ", new String[]{"foo", "bar"});
String.join(" > ", "foo", "bar");
or String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
String.join(" > ", Arrays.asList("foo", "bar"));
Since Java 8 we can use StringJoiner (instead of originally used StringBulder) and simplify our code.
Also to avoid recompiling " *" regex in each call of matches(" *") we can create separate Pattern which will hold its compiled version in some field and use it when needed.
private static final Pattern SPACES_OR_EMPTY = Pattern.compile(" *");
public static String implode(String separator, String... data) {
StringJoiner sb = new StringJoiner(separator);
for (String token : data) {
if (!SPACES_OR_EMPTY.matcher(token).matches()) {
sb.add(token);
}
}
return sb.toString();
}
With streams our code can look like.
private static final Predicate<String> IS_NOT_SPACES_ONLY =
Pattern.compile("^\\s*$").asPredicate().negate();
public static String implode(String delimiter, String... data) {
return Arrays.stream(data)
.filter(IS_NOT_SPACES_ONLY)
.collect(Collectors.joining(delimiter));
}
If we use streams we can filter elements which Predicate. In this case we want predicate to accept strings which are not only spaces - in other words string must contain non-whitespace character.
We can create such Predicate from Pattern. Predicate created this way will accept any strings which will contain substring which could be matched by regex (so if regex will look for "\\S" predicate will accept strings like "foo ", " foo bar ", "whatever", but will not accept " " nor " ").
So we can use
Pattern.compile("\\S").asPredicate();
or possibly little more descriptive, negation of strings which are only spaces, or empty
Pattern.compile("^\\s*$").asPredicate().negate();
Next when filter will remove all empty, or containing only spaces Strings we can collect rest of elements. Thanks to Collectors.joining we can decide which delimiter to use.
Original answer (before Java 8)
public static String implode(String separator, String... data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length - 1; i++) {
//data.length - 1 => to not add separator at the end
if (!data[i].matches(" *")) {//empty string are ""; " "; " "; and so on
sb.append(data[i]);
sb.append(separator);
}
}
sb.append(data[data.length - 1].trim());
return sb.toString();
}
You can use it like
System.out.println(implode(", ", "ab", " ", "abs"));
or
System.out.println(implode(", ", new String[] { "ab", " ", "abs" }));
Output ab, abs
Why so serious?
Try StringUtils.join(new String[] {"Hello", "World", "!"}, ", ") !
Here is an Android-specific answer that may be helpful to some:
String combined = TextUtils.join(",", new String[]{"Red", "Green", "Blue"});
// Result => Red,Green,Blue
Be sure to import the TextUtils class:
import android.text.TextUtils;
You'd have to add your strings to an ArrayList, remove empty ones, and format it accordingly:
public static String createAddressString( String street, String zip_code, String country) {
List<String> list = new ArrayList<String>();
list.add( street);
list.add( zip_code);
list.add( country);
// Remove all empty values
list.removeAll(Arrays.asList("", null));
// If this list is empty, it only contained blank values
if( list.isEmpty()) {
return "";
}
// Format the ArrayList as a string, similar to implode
StringBuilder builder = new StringBuilder();
builder.append( list.remove(0));
for( String s : list) {
builder.append( ", ");
builder.append( s);
}
return builder.toString();
}
Additionally, if you had String[], an array of strings, you can easily add them to an ArrayList:
String[] s;
List<String> list = new ArrayList<String>( Arrays.asList( s));
Using Streams (for Java 8 and later) would be an alternate possible solution for this.
You are required to import
java.util.stream.Collectors;
to use the join process
You may use:
Arrays.asList("foo","bar").stream().collect(Collectors.joining(","));
to achieve the desired result.
A simple Implode
public static String implode(String glue, String[] strArray)
{
String ret = "";
for(int i=0;i<strArray.length;i++)
{
ret += (i == strArray.length - 1) ? strArray[i] : strArray[i] + glue;
}
return ret;
}
You can create overloads for it..
The above it equivalent of php implode.
Here is what you want:
import java.lang.*
public static String customImplode(String glue, String[] strArray)
{
String ret = "";
for(int i=0;i<strArray.length;i++)
{
if (strArray[i].trim() != "")
ret += (i == strArray.length - 1) ? strArray[i] : strArray[i] + glue;
}
return ret;
}
Here's my implode implementation:
/**
* Implodes the specified items, gluing them using the specified glue replacing nulls with the specified
* null placeholder.
* #param glue The text to use between the specified items.
* #param nullPlaceholder The placeholder to use for items that are <code>null</code> value.
* #param items The items to implode.
* #return A <code>String</code> containing the items in their order, separated by the specified glue.
*/
public static final String implode(String glue, String nullPlaceholder, String ... items) {
StringBuilder sb = new StringBuilder();
for (String item : items) {
if (item != null) {
sb.append(item);
} else {
sb.append(nullPlaceholder);
}
sb.append(glue);
}
return sb.delete(sb.length() - glue.length(), sb.length()).toString();
}
public static String implode(List<String> items, String separator) {
if (items == null || items.isEmpty()) {
return null;
}
String delimiter = "";
StringBuilder builder = new StringBuilder();
for (String item : items) {
builder.append(delimiter).append(item);
delimiter = separator;
}
return builder.toString();
}
Use this simple function:
private String my_implode(String spacer, String[] in_array){
String res = "";
for (int i = 0 ; i < in_array.length ; i++) {
if (!res.equals("")) {
res += spacer;
}
res += in_array[i];
}
return res;
}
Use:
data_arr = {"d1", "d2", "d3"};
your_imploded_text = my_implode(",", data_arr);
// Output: your_imploded_text = "d1,d2,d3"