String类的一些方法 和 StringBuffer用法

String aa="abcdefg";

//  包括  有重复字母的情况!!!!!!!!!!!!!
//连接字符串
aa+="hijk";
System.out.println("连接后为"+aa);


//获取指定字符
char bb=aa.charAt(0);
System.out.println(aa+"里索引为0的字符为"+bb);

//获取子字符串出现的索引

int index1=aa.indexOf("b");
System.out.println("b 第一次出现的索引为"+index1);

//从指定位置往后查
int index2=aa.indexOf("d", 2);
System.out.println("从索引2的位置往后查 d  的位置为"+index2);

//获取最后一次出现的索引
int index3=aa.lastIndexOf("b");
System.out.println("b最后一次出现的索引为"+index3);

//从指定位置往前查
int index4 =aa.lastIndexOf("c", 1);
System.out.println(index4);


//判断字符串首尾内容
//1,  判断尾部
boolean ii=aa.endsWith("ijk");
System.out.println(ii);

//2, 判断首部
boolean jj=aa.startsWith("abc");
System.out.println(jj);


//获取字符串数组
char arr[]=aa.toCharArray();
for (char c : arr) {
System.out.print(c+" ");
}System.out.println();

//判断字符串是否存在

boolean c1=aa.contains("bc");
System.out.println(c1);
// 用indexOf 判断是否存在     / indexOf  返回值为-1 就表示不存在
if(aa.indexOf("b")>-1){

System.out.println("b存在");

}


//截取字符串
String a1=aa.substring(3);
System.out.println("从索引为3的位置开始截取"+a1);
String a2=aa.substring(3, 6);
System.out.println("从索引为3到6的位置截取"+a2);

//分割字符串
String ff="天王盖地虎,玉帝日王母,宝塔镇河妖,段友吊缠腰";
String aff[]=aa.split(",");
for (String string : aff) {
System.out.println(string);

}


 StringBuffer sb = new StringBuffer("Hello "); 
sb.append("world");   //在sb尾部追加一个字符串, 此时变成 Hello world; 
sb.charAt(1) ;  //返回下标为1的字符 此处是 e 
sb.insert(1,"d");  //在 1 处插入新的字符串 d  此时变为 Hedllo world; 
sb.reverse();  //反转字符 此时变成    dlrow olldeH 
sb.delete(1,2);  //删除字符串  此时变为Hllo world 
sb.replace(3,4,"new");  //替换字符串  从 3开始到4结束  此时变为  Hllnewworld  





猜你喜欢

转载自blog.csdn.net/qzy623569881/article/details/80071732