To manipulate string, java.lang.StringBuffer class comes with many methods, otherwise, which will take long laborious coding as in C/C++. One such method is setCharAt(int, char) that replaces a single character in the string buffer. Now read setCharAt() StringBuffer.
What Java API says of setCharAt() StringBuffer:
- public synchronized void setCharAt(int index1, char1): Replaces the character in the StringBuffer at index number index1 with character char1.
Following setCharAt() StringBuffer example illustrates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Demo { public static void main(String args[]) { StringBuffer sb1 = new StringBuffer("ABCDEFGHI"); System.out.println("Original string buffer sb1: " + sb1); sb1.setCharAt(0, 'a'); sb1.setCharAt(4, 'e'); System.out.println("String buffer sb1 after setting char: " + sb1); sb1.setCharAt(10, 'y'); } } |

Output screenshot on setCharAt() StringBuffer Example
sb1.setCharAt(0, 'a');
sb1.setCharAt(4, 'e');
sb1.setCharAt(10, 'y');
setCharAt(0, 'a') replaces A (at 0 index number) with a and setCharAt(4, 'e') replaces E (at 4 index number) with e. We have seen earlier how to replace a group of characters.
setCharAt(10, 'y') throws StringIndexOutOfBoundsException as 10th index number does not exist in sb1.
A similar example exists replacing a group of characters "replace() StringBuffer Example".