2011-10-12 82 views
4

在Java ME中,我需要做一个简单的字符串替换: String.format("This string contains placeholders %s %s %s", "first", "second", "third");
占位符不必是字符串的结尾:Java ME:格式化字符串最简单的方法是什么?

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

但是,据我所看到的,String.format方法不是在J2ME中使用。什么是替代这个?如何在不编写自己的函数的情况下实现简单的字符串格式化?

回答

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

thanx,我结束了使用我自己的功能,但thanx无论如何。 – Maggie

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

对不起,也许我不清楚enoguh。占位符不必位于字符串的末尾,它们可以位于句子中的任何位置。我会更新我的问题。 – Maggie

+1

这是不正确的答案: -/ – bharath

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"); 
相关问题