开发者

Java ME: easiest way to format strings?

In Java ME, I need to do a simple string substitution: String.format("This string contains placeholders %s %s %s", "first", "second", "third");

Placeholders don't have to be at the end of the string:

String.format ("Your name is %s and you 开发者_StackOverflow社区are %s years old", "Mark", "18");

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


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

Something like this:

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"})
    );
  }
}


I've ended writing my own function, it 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");


String a="first",b="second",c="third";
String d="This string content placeholders "+a+" "+b+" "+c;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜