本帖最后由 itheima_llt 于 2015-4-12 15:18 编辑
想发一个StringBuffer的练习,怎么不让发了?见下面那张截图!
- class StringBufferDemo
- {
- public static void main(String[] args)
- {
- //add();
- //delete();
- update();
- }
- //1 存储
- public static void add()
- {
- StringBuffer sb = new StringBuffer();
- StringBuffer sb1 = sb.append("abcdefg");
- System.out.println(sb.toString());
- System.out.println(sb==sb1);//true
- sb.insert(1,"23");
- System.out.println(sb.toString());
- }
- //2 删除
- public static void delete()
- {
- StringBuffer sb = new StringBuffer("abcd123efgh");
- sb.delete(4,7);
- System.out.println(sb.toString());//结果abcdefgh.删除包含头不包含尾
- sb.deleteCharAt(7);
- System.out.println(sb.toString());//结果abcdefg
- sb.delete(0,sb.length());//sb被清空了,结果为空串
- }
- //3 修改
- public static void update()
- {
- StringBuffer sb = new StringBuffer("abcdefgh");
- sb.replace(0,3,"Hello java");
- System.out.println(sb.toString());//结果Hello javadefgh
- sb.setCharAt(0,'h');
- System.out.println(sb.toString());//结果hello javadefgh
- //4 反转
- sb.reverse();
- System.out.println(sb.toString());//结果hgfedavaj olleh
- //5 将缓冲区中指定数据存储到指定字符数组的指定位置中
- char[] ch = new char[7];
- sb.getChars(0,5,ch,0);
- System.out.println(new String(ch));//运行结果hgfed
- }
- }
复制代码
|
|