本文共 1127 字,大约阅读时间需要 3 分钟。
由于字符串是常量,一旦创建,其内容及长度就不可改变。如果需要改变则只能创建新的字符串。为了便于对字符串的修改,在JDK中提供了StringBuffer类。与String最大的区别在于可以修改内容及长度。具体用法见下边代码示例:
public class Main{ public static void main(String[] args)throws Exception{ System.out.println("1.添加操作..............."); add(); System.out.println("2.删除操作..............."); remove(); System.out.println("3.修改操作..............."); alter(); } public static void add() { StringBuffer sb=new StringBuffer();//创建对象 sb.append("abcdefg");//在末尾添加字符 System.out.println("append添加结果:"+sb); sb.insert(2, "123");//在指定位置添加字符 System.out.println("insert插入结果:"+sb); } public static void remove() { StringBuffer sb=new StringBuffer("abcdefg"); sb.delete(1, 5); //删除指定范围 System.out.println("删除指定位置后的结果:"+sb); sb.deleteCharAt(2); //删除指定位置 System.out.println("删除指定位置后的结果:"+sb); sb.delete(0, sb.length()); System.out.println("清空后的结果:"+sb); } public static void alter() { StringBuffer sb=new StringBuffer("abcdefg"); sb.setCharAt(1,'p'); //修改指定位置字符 System.out.println("修改后的结果:"+sb); sb.replace(1, 3, "qq"); //替换指定位置字符串或字符 System.out.println("修改后的结果:"+sb); System.out.println("字符串反转后的结果:"+sb.reverse()); }}
转载地址:http://fuohn.baihongyu.com/