2011-10-12 81 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"); 
相關問題