StringBuffer is a peer class of String. While String class creates strings of fixed lengths, StringBuffer class creates strings of flexible length that can be modified in terms of both length and content. We can insert characters and substring in the middle of the string or append another string to the end. Given below are some of the methods used in String manipulations: 1. setCharAt Modifies the nth character to x s1.setCharAt(n, 'x'); 2. append Appends the string s2 to s1 at the end s1.append(s2); 3. insertAt Inserts the string s2 at the position n of the string s1 s1.insert(n, s2); 4. setLength Sets the length of the String s1 to n. If n < s1.length( ), s1 is truncated. If n > s1.length(), zeros are added to s1. s1.setLength(n); Given below is an example, which explains how the methods of StringBuffer class are used to manipulate the strings: class stringManipulation { public static void main(String args[]) { // str is an object of class StringBuffer StringBuffer str = new StringBuffer("Object language"); System.out.println("Original String : "+str); System.out.println("Length of String is : "+ str.length()); for(int i = 0; i < str.length(); i++) { int p = i + 1; // accessing characters in a string System.out.println("Character at position : " + p +" is : " + str.charAt(i)); } String aString = new String(str.toString()); int pos = aString.indexOf("language"); // inserting a string in the middle str.insert(pos, "Oriented"); System.out.println("Modified string : " + str); // Modifying character at position 6 str.setCharAt(6, '`'); System.out.println("String now : " + str); // Appending a string at the end str.append("improves security : "); System.out.println("Append string : "+str); } } |
Course Content > Session 4 >