Monday 16 March 2009

Message Formating J2ME

Java has got a MessageFormat(but not J2ME) class to replace arguments in text.

For example, “You have received {1} new {0} messages” can be formatted by each client by providing “3” as first argument and “bubble” as second one.. To learn more about it, just Google it.

Now, the problem I faced was that MessageFormat is not supported in J2ME. Therefore, I created my own class to format those strings.

Please copy and paste the code in a notepad for you to see it clearly. Enjoy! ;)

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

public class Formatter{

public String format(String text,String [] arguments){

if(text != null) {
StringBuffer buf = new StringBuffer();
int start = text.indexOf("{");
int end = text.indexOf("}",start);

if (start < 0 || end <= start || args == null || args.length == 0 ) return text;

buf.append(text.substring(0,start));

while (start >= 0 && end > start) {
try {
String replaceWith = args[Integer.parseInt(text.substring(start+1,end))];
buf.append(replaceWith != null ? replaceWith : "");
} catch (Exception e){
buf.append(text.substring(start,end+1));
}
start = text.indexOf("{",end);
buf.append(start >= 0 ? text.substring(end+1,start) : text.substring(end+1));
end = text.indexOf("}",start);
}
return buf.toString();
} else {
return ("?" + text + "?");
}
}

No comments: