StringBuffer char operation
In this chapter you will learn:
- How to get a char from a certain index inside a StringBuffer
- How copy part of a StringBuffer to a char array
- How to update a char in a StringBuffer
Get a char from a certain index inside a StringBuffer
The value of a single character can be obtained from a StringBuffer via the charAt( ) method.
char charAt(int index)
returns the char value in this sequence at the specified index.
public class Main {
public static void main(String[] argv) {
StringBuffer sb = new StringBuffer();
sb.append("java2s.com");
//from ja v a 2 s.com
char ch = sb.charAt(0);
System.out.println(ch);
}
}
The output:
Copy to a char array
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
copies characters from StringBuffer into the destination character array dst.
public class Main {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer("hello there");
/*ja v a2 s.co m*/
System.out.printf("buffer = %s\n", buffer.toString());
System.out.printf("Character at 0: %s\nCharacter at 4: %s\n\n", buffer.charAt(0), buffer
.charAt(4));
char charArray[] = new char[buffer.length()];
buffer.getChars(0, buffer.length(), charArray, 0);
System.out.print("The characters are: ");
}
}
Update char in a StringBuffer
You can set the value of a character within a
StringBuffer
using setCharAt( )
.
void setCharAt(int index, char ch)
set character at the specified
index
is set to ch
.
The following example demonstrates charAt( ) and setCharAt( ):
public class Main {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("java2s.com");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
//from ja v a 2 s .c o m
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- Replace string content in a StringBuffer
- Reverse a StringBuffer
- Delete characters within a StringBuffer
Home » Java Tutorial » String