Java入门——StringBuffer类

Java入门——StringBuffer类


认识StringBuffer类

  如果一个字符串需要经常被改变,就需要使用StringBuffer类。(String类型的变量一旦声明就很难改变,若想改变,必须改变引用地址)!  



 字符串的连接操作

  在程序书中使用append方法可以进行字符串的连接操作。

package Sep22;

public class StringBufferDemo01 {
	public static void main(String[] args) {
		StringBuffer buf=new StringBuffer();
		buf.append("Hello");//利用append添加内容
		buf.append(" World!").append("!!!!");//连续添加内容
		buf.append("
");
		buf.append("数字:").append(1).append("
");
		System.out.println(buf);
		
	}
}

  

Hello World!!!!!
数字:1

  


 在任意位置为StringBuffer添加内容

  可以直接使用insert()方法。

package Sep22;

public class StringBufferDemo03 {
	public static void main(String[] args) {
		StringBuffer buf=new StringBuffer();
		buf.append(" wodld");
		buf.insert(0, "hello");
		System.out.println(buf);
		
	}
}
hello wodld

字符串反转操作

package Sep26;

public class StringBufferDemo04 {
	public static void main(String[] args) {
		StringBuffer buf = new StringBuffer();
		buf.append("word");
		buf.insert(0, "hello");
		String str=buf.reverse().toString();
		System.out.print(str);
	}
}
drowolleh

替换指定范围内的内容

repalce()函数

字符串截取

substring()

删除指定范围的字符串

delete();

查找指定的内容是否存在

indexOf();

  

原文地址:https://www.cnblogs.com/BoscoGuo/p/5896405.html