开发者

What's the Java feature that lets you write into a String?

I've done this in Java before but I can't remember how exactly.

You create a String:

开发者_如何学Go
String foo = "She %s sea shells by the seashore.";

Then you can write into the String the word "sells".

What do you use for that?


String myString = "sells";
String foo = String.format("She %s sea shells by the seashore.", myString);


You're looking for the Formatter class, or the String.format convenience method:

String.format(foo, "sells");


String.format?

Object a[] = { "Real's HowTo", "http://www.any.com" ,
        java.util.Calendar.getInstance()};

String s = String.format("Welcome %1$s at %2$s ( %3$tY %3$tm %3$te )", a);
System.out.println(s);
//  output : Welcome Real's HowTo at http://www.any.com (2010 06 26)


You can use the String.Format function for this.


Straight from the source (and my bookmarks)...

   StringBuilder sb = new StringBuilder();
   // Send all output to the Appendable object sb
   Formatter formatter = new Formatter(sb, Locale.US);

   // Explicit argument indices may be used to re-order output.
   formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d");

UPDATE: Sorry meant to include the link: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜