StringBuffer Operations
In this chapter you will learn:
- Replace string content in a StringBuffer
- Reverse a StringBuffer
- Delete characters within a StringBuffer
Replace string content in a StringBuffer
StringBuffer replace(int start, int end, String str)
can replace one set of characters with another set inside a StringBuffer
.
It replaces the characters in a substring of
this sequence with characters in the specified String.
The substring being replaced is specified by
the indexes startIndex
and endIndex
.
substring at startIndex
through endIndex-1
is replaced.
The replacement string is passed in str.
The resulting StringBuffer
object is returned.
The following program demonstrates replace( ):
public class Main {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
// jav a 2s .c o m
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
Here is the output:
Reverse a StringBuffer
You can reverse the characters within a StringBuffer
object using reverse()
.
StringBuffer reverse()
causes this character sequence to be replaced by the reverse of the sequence.
public class Main {
public static void main(String[] argv) {
StringBuffer sb = new StringBuffer();
sb.append("java2s.com");
/* j av a 2s. co m*/
sb.reverse();
System.out.println(sb.toString());
}
}
The output:
Delete characters within a StringBuffer
You can delete characters within a StringBuffer
by
using the methods delete( )
and deleteCharAt( )
.
StringBuffer delete(int start, int end)
-
StringBuffer deleteCharAt(int index)
removes the char at the specified position in this sequence.
removes the characters in a substring of this sequence.
public class Main {
public static void main(String[] argv) {
StringBuffer sb = new StringBuffer();
sb.append(true);/*from ja va2 s .c o m*/
sb.append("java2s.com");
sb.delete(1, 2);
System.out.println(sb.toString());
}
}
The output:
Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:
public class Main {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
/* j a v a2 s .c o m*/
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
The following output is produced:
Next chapter...
What you will learn in the next chapter: