Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String append with format in android

Tags:

string

android

Anybody help me please. I don't know how to append the String with format in android similar to this:

String key = "";
append("%d-%d-%d", 0, 1, 2));

Please give me an example. Thank you in advance.

like image 986
Siemhong Avatar asked Mar 21 '13 04:03

Siemhong


2 Answers

Use StringBuilder or StringBuffer but with adequate initial capacity to avoid re-allocation. The default capacity is 16, so once you exceed that, the data has to be copied into a new bigger place. Use append not +.

int integer = 5;

StringBuilder s = new StringBuilder(100);
 s.append("something");
 s.append(integer);
 s.append("more text");
like image 70
Furqi Avatar answered Oct 06 '22 05:10

Furqi


You can use either StringBuffer or StringBuilder

public class Test {

public static void main(String args[]) {
  StringBuffer sb = new StringBuffer("Test");
  sb.append(" String Buffer");
  System.out.println(sb); 
}  
}

This produces following result:

Test String Buffer

StringBuilder:

StringBuilder strBuilder = new StringBuilder("foo");
strBuilder.append("bar");
strBuilder.append("baz");
String str = strBuilder.toString();

For format, try

String.format("Hello %1$s, your name is %1$s and the time is %2$t", name, time)
like image 41
Linga Avatar answered Oct 06 '22 07:10

Linga