Java ME: the easiest way to format strings?

In Java ME, I need to do a simple string replacement: String.format("This string contains placeholders %s %s %s", "first", "second", "third") ;
Placeholders should not be at the end of the line:

 String.format ("Your name is %s and you are %s years old", "Mark", "18"); 

But as far as I can see, the String.format method String.format not available in j2me. What is an alternative to this? How can I achieve simple string formatting without writing my own function?

+4
source share
3 answers

You're out of luck here, Java ME has a very limited API, so you need to write your own code for this.

Something like that:

 public class FormatTest { public static String format(String format, String[] args) { int argIndex = 0; int startOffset = 0; int placeholderOffset = format.indexOf("%s"); if (placeholderOffset == -1) { return format; } int capacity = format.length(); if (args != null) { for (int i=0;i<args.length;i++) { capacity+=args[i].length(); } } StringBuffer sb = new StringBuffer(capacity); while (placeholderOffset != -1) { sb.append(format.substring(startOffset,placeholderOffset)); if (args!=null && argIndex<args.length) { sb.append(args[argIndex]); } argIndex++; startOffset=placeholderOffset+2; placeholderOffset = format.indexOf("%s", startOffset); } if (startOffset<format.length()) { sb.append(format.substring(startOffset)); } return sb.toString(); } public static void main(String[] args) { System.out.println( format("This string contains placeholders %s %s %s ", new String[]{"first", "second", "third"}) ); } } 
+2
source

I ended up writing my own function, this might help someone:

 static String replaceString(String source, String toReplace, String replaceWith) { if (source == null || source.length() == 0 || toReplace == null || toReplace.length() == 0) return source; int index = source.indexOf(toReplace); if (index == -1) return source; String replacement = (replaceWith == null) ? "" : replaceWith; String replaced = source.substring(0, index) + replacement + source.substring(index + toReplace.length()); return replaced; } 

and then I just call it 3 times:

 String replaced = replaceString("This string contains placeholders %s %s %s", "%s", "first"); replaced = replaceString(replaced, "%s", "second"); replaced = replaceString(replaced, "%s", "third"); 
+1
source
 String a="first",b="second",c="third"; String d="This string content placeholders "+a+" "+b+" "+c; 
-1
source

All Articles