Thursday, December 22, 2011

Java's character and assorted string classes support text-processing - 22


·  public String toString() creates a new String object containing the same characters as the current StringBuffer's value array and returns a reference to String. The following code demonstrates toString() in a more efficient (and faster) alternative to String's concat(String str) method for concatenating strings within a loop:
String s = "abc";
String t = "def";
     
StringBuffer sb = new StringBuffer (2000000);
for (int i = 0; i < 100000; i++)
     sb.append (s).append (t);
String u = sb.toString ();
sb = null;
System.out.println (u);

As the output is large, I don't include it here. Try converting this code into a program and compare its performance with the earlier String s = "abc"; String t = "def"; String u = ""; for (int i = 0; i < 100000; i++) u = u.concat (s).concat (t); code.

For a demonstration of StringBuffer's append(String str) and toString() methods, and the StringBuffer() constructor, examine Listing 4's DigitsToWords, which converts an integer value's digits to its equivalent spelled-out form (for example, 10 verses ten):

No comments: