StringBuffer charAt() and setCharAt()


charAt() and setCharAt()

The value of a single character is obtained from a StringBuffer through the charAt() method. You can set a character value using setCharAt() in the StringBuffer. Their simple form is shown here :

char charAt(int where)
void setCharAt(int where, char ch)

For charAt(), where specifies the index of the character is obtained. For setCharAt(), where specific the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the string.


Example

Program
public class Main 
{
  public static void main(String[] args) 
  {
    StringBuffer sb = new StringBuffer("Hello World");
    System.out.println("buffer before = " + sb);
    System.out.println("charAt(2) before = " + sb.charAt(2));
    
    sb.setCharAt(2,'i');
    System.out.println("buffer after = " + sb);
    System.out.println("charAt(2) after = " + sb.charAt(2));
  }
}

getChars()

To copy a substring of a StringBuffer into an array, use the gerChars() method. It has this simple form :

void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)

Here, sourceStart specifies the index of the beginning of the substring and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd -1. The array that will receive the characters is specified by the target. The index within the target at which the substring will be copied is passed in targetStaart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.