Java StringBuffer setLength()方法

java.lang.StringBuffer.setLength()方法设置字符序列的长度。 序列更改为新的字符序列,其长度由参数指定。

1 语法

public void setLength(int newLength)

2 参数

newLength : 这是新的长度。

3 返回值

此方法不返回任何值。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java StringBuffer setLength()方法
 */
import java.lang.*;
public class StringBufferDemo {
   public static void main(String[] args) {
      StringBuffer buff = new StringBuffer("tutorials");
      System.out.println("buffer1 = " + buff);  
      // length of stringbuffer
      System.out.println("length = " + buff.length());
      // set the length of stringbuffer to 5
      buff.setLength(5);
      // print new stringbuffer value after changing length
      System.out.println("buffer2 = " + buff);
      // length of stringbuffer after changing length
      System.out.println("length = " + buff.length());
   }
}

输出结果为:

buffer1 = tutorials
length = 9
buffer2 = tutor
length = 5

 

热门文章

优秀文章