Java ME:格式化字符串的最简单方法?

时间:2011-10-12 10:01:53

标签: java java-me string-formatting

在Java ME中,我需要做一个简单的字符串替换: String.format("This string contains placeholders %s %s %s", "first", "second", "third");
占位符不必位于字符串的末尾:

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

但是,据我所知,String.format方法在j2me中不可用。有什么替代方案?如何在不编写自己的函数的情况下实现简单的字符串格式化?

3 个答案:

答案 0 :(得分:2)

你在这里运气不好,Java ME的API非常有限,所以你必须为此编写自己的代码。

这样的事情:

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

答案 1 :(得分:1)

我已经完成了自己的功能,可能对某人有所帮助:

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

然后我只叫它3次:

String replaced = replaceString("This string contains placeholders %s %s %s", "%s", "first");
replaced = replaceString(replaced, "%s", "second");
replaced = replaceString(replaced, "%s", "third");

答案 2 :(得分:-1)

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