韩顺平Java27——包装类03(StringBuffer、StringBuilder)
StringBuffer类
基本介绍
-
StringBuffer与String比较
-
构造方法
1.
2.
3.
-
StringBuffer与String相互转换
1.String ->StringBuffer
(1)
(2)
2.StringBuffer ->String
(1)
(2)
-
StringBuffer常用方法
1.append()
StringBuffer stringBuffer = new StringBuffer("hello"); stringBuffer.append("world"); System.out.println(stringBuffer); //这里追进去使用的是重写的toString方法(如下)
//helloworld
@Override public synchronized String toString() { if (toStringCache == null) { toStringCache = Arrays.copyOfRange(value, 0, count); } return new String(toStringCache, true); }
2.delete()
3.replace()
4.indexof
5.insert
-
练习
1.
2. 格式化价格(每三位加一个逗号)
Scanner scanner = new Scanner(System.in); System.out.println("请输入价格:"); String s = scanner.next(); StringBuffer stringBuffer = new StringBuffer(s); for (int i = stringBuffer.lastIndexOf(".") - 3; i > 0; i -= 3) { stringBuffer = stringBuffer.insert(i, ','); } System.out.println("价格格式化后为:"+"\n"+stringBuffer);
StringBuilder类
-
基本介绍
-
继承关系
-
常用方法
String、StringBuffer、StringBuilder比较
-
效率比较:
-
选择的原则
本文来自博客园,作者:紫英626,转载请注明原文链接:https://www.cnblogs.com/recorderM/p/15739501.html