标题: 非常全的StringBuffer使用方法 [打印本页] 作者: 仲德明 时间: 2015-6-7 22:24 标题: 非常全的StringBuffer使用方法 public class UsingStringBuffer {
//查找字符串
public static void testFindStr(){
StringBuffer s = new StringBuffer("This is a StringBuffer!");
System.out.println(s.indexOf("is"));
System.out.println(s.indexOf("is",4));
System.out.println(s.lastIndexOf("is",1));
}
//截取字符串
public static void testSubStr(){
StringBuffer s = new StringBuffer("This is a StringBuffer");
System.out.println(s.substring(2));
System.out.println(s.substring(2,5));
}
//获取某个位置上的字符
public static void testCharAt(){
StringBuffer s = new StringBuffer("This is a StringBuffer");
System.out.println(s.charAt(2));
}
//添加各种数据类型到字符串
public static void testAppend(){
StringBuffer s = new StringBuffer("This is a StringBuffer");
System.out.println(s.append("is"));
System.out.println(s.append(2));
System.out.println(s.append('I'));
System.out.println(s.append(new char[]{' ', 'a','m'}));
System.out.println(s.append(true));
}
//删除字符串中的数据
public static void testDelete(){
StringBuffer sb = new StringBuffer("This is a StringBuffer!");
System.out.println(sb.delete(1,5));
System.out.println(sb.deleteCharAt(1));
}
//向字符串中插入各种数据
public static void testInsert(){
StringBuffer sb = new StringBuffer("This is a StringBuffer");
System.out.println(sb.insert(2, "Hao"));
System.out.println(sb.insert(3,'N'));
System.out.println(sb.insert(5,new char[]{'s','a','d'}));
System.out.println(sb.insert(2,34.23));
}
//替换
public static void testReplace(){
StringBuffer sb = new StringBuffer("This is a StringBuffer!");
System.out.println(sb.replace(2,5 ,"hello "));
}
//将字符串倒序
public static void reverseStr(){
StringBuffer sb = new StringBuffer("This is a StringBuffer!");
System.out.println(sb.reverse());
}