StringBuilder class provides more
power over the normal String class. It allows you modify the content of a string easily. With the StringBuilder class, you can insert different types of values in to a string at any position, delete a part of the string, reverse string, etc. These operations are not found in the String class.
To insert a value (a character, an array of characters, a number, or string) to any position of the string wrapped by the StringBuilder object, you can use the following insert methods as shown below:
-insert(int position, char c) inserts the character, c in to the string.
-insert (int position, char[] cs) inserts the array of characters, cs in to the string.
-insert(int position, int i) inserts the integer value, i in to the string.
-insert(int position, long l) inserts the long integer value, l to the string.
-insert(int position, double d) inserts the double value, d to the string.
-insert(int position, String str) inserts the string value, str to the string.
Example:
String oldString="StringBuilder Java";
StringBuilder sb=new StringBuilder(oldString);
sb.insert(sb.lastIndexOf(" "), " in"); //insert in to the string
System.out.println(sb);
Note: The lastIndexOf(String str) method returns the last position of the argument str in the string. To convert back from the StringBuilder object to a normal String object, you will use the toString() method of the StringBuilder.
If you want to delete a part of the string, you will use the delete(int start,int end) method. Similarly to the insert method, the delete method will modified the content of StringBuilder object.
Example:
String oldString="StringBuilder Java";
StringBuilder sb=new StringBuilder(oldString);
sb.delete(0, sb.lastIndexOf(" ")); //remove the StringBuilder from the string
System.out.println(sb);
Besides insert, and delete method, the StringBuilder class has the reverse method that can be used to reserve the sequence of characters in the string. This method is also not found in the normal String class.
Example:
String oldString="StringBuilder Java";
StringBuilder sb=new StringBuilder(oldString);
sb.reverse();
System.out.println(sb);
No comments:
Post a Comment