Java 基础类库(String 与 StringBuffer的转换)

范例1:StringBuffer基本使用
public class Demo {
	public static void main(String[] args) {
		// StringBuffer不能直接复制实例化
		StringBuffer buf = new StringBuffer();
		buf.append("Hello").append("World").append("!!");
		change(buf);//引用传递
		System.out.println(buf);
	}

	public static void change(StringBuffer temp) {
		temp.append("\n").append("Java");
	}
}

=============分割线=============

范例2:StringBuffer类的构造方法:public StringBuffer(String str)

public class Demo {
	public static void main(String[] args) {
		StringBuffer buf = new StringBuffer("Hello World!");
		System.out.println(buf);
	}

}

=============分割线=============

范例3:append()方法:public StringBuffer append(String str)

public class Demo {
	public static void main(String[] args) {
		StringBuffer buf = new StringBuffer("Hello");
		buf.append("\tJava");
		System.out.println(buf);
	}

}

=============分割线=============

范例4:将StringBuffer转为String

·利用toString()将StringBuffer转为String

public class Demo {
	public static void main(String[] args) {
		StringBuffer buf = new StringBuffer("Hello");
		String str = buf.toString();
		System.out.println(str);
	}

}

=============分割线=============

范例5:String类里面有提供和StringBuffer比较的方法:public boolean contentEquals(StringBuffer sb)

public class Demo {
	public static void main(String[] args) {
		StringBuffer buf = new StringBuffer("Hello");
		System.out.println("Hello".contentEquals(buf));
	}

}

=============分割线=============

范例6:字符串反转:public StringBuffer reverse();

public class Demo {
	public static void main(String[] args) {
		StringBuffer buf = new StringBuffer("霸王别姬");
		System.out.println(buf.reverse());
	}

}

=============分割线=============

范例7:指定位置添加数据:public StringBuffer insert(int offset,数据类型 变量);

public class Demo {
	public static void main(String[] args) {
		StringBuffer buf = new StringBuffer("Hello");
		buf.insert(5, " Java!").insert(0, "欢迎!");
		System.out.println(buf);
	}

}

=============分割线=============

范例8:删除部分数据:public StringBuffer delete(int start ,int end)

public class Demo {
	public static void main(String[] args) {
		StringBuffer buf = new StringBuffer("Hello World");
		System.out.println(buf.delete(0, 5));
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值