String类
substring方法
字符串截取方法,返回截取的字符串
privateString hello="Helloworld";
/**
* 字符串截取
*/
@Test
public voidtest(){
System.out.println(hello);
String str=hello.substring(1,4);//从第一个索引值开始,到第二个索引值结束,不包含第二个索引值
String str1=hello.substring(3);//从索引值开始,一直到结束
System.out.println(str);
System.out.println(str1);
}
split方法
字符串拆分的方法,根据字符串中的符号或者特殊字符,来拆分字符串,得到拆分后的数组
/**
* 字符串拆分成数组
*/
@Test
public voidtest1(){
String str="111,222,333";
String[] arr=str.split(",");
System.out.println(Arrays.toString(arr));
}
indexof方法
字符查找的方法,返回值为整数型,返回指定字符在次字符串中首次出现的位置(从0开始),如果没有就返回-1
/**
* 查找字符串中是否存在该字符(或字符串)
*/
@Test
public voidtest2(){
String email="156483394134524@163.com";
if(email.indexOf("@")!=-1){
System.out.println("这是一个邮箱地址");
System.out.println("@的位置:"+email.indexOf("@"));
}else{
System.out.println("这不是一个邮箱地址");
}
}
@Test
public voidtest3(){
int i=hello.indexOf("e");
System.out.println(i);
int j=hello.lastIndexOf("o");//从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引
System.out.println(j);
}
replace方法
字符串替换方法,在此字符串中找到需要替换的字符串,然后换成自己想要的字符或者字符串
/**
* 替换字符串中的字符或者字符串
*/
@Test
public voidtest4(){
String str=hello.replace("world", "我的Java世界");
System.out.println(str);
}
trim方法
字符串去空格的方法,去掉字符串两边的空格,返回值是去掉的空格的字符串
/**
* 去掉字符串两边的空格
*/
@Test
public voidtest5(){
String str=" 今天天气还不错哦! ";
System.out.println(str);
String str1=str.trim();
System.out.println(str1);
}
封装类和字符串的相互转换
封装类指的是部分基本数据类型的对象行使
int ->Integer
long->Long
double->Double
float->Float
Boolean->Boolean
/**
* 包装类
*/
@Test
public voidtest6(){
inti=Integer.parseInt("100");
doublej=Double.parseDouble("12.45");
booleany=Boolean.parseBoolean("true");
System.out.println(i);
System.out.println(j);
System.out.println(y);
StringBuff类
append方法
在字符串或者字符后面添加新的字符
/**
*append:将某个字符或字符串追加到原字符序列的末尾
*/
@Test
public voidtest1() {
StringBuffer sb= new StringBuffer("HelloWorld");
sb.append("MyJava");
System.out.println(sb);
}
Insert方法
/**
*insert:将某个字符或字符串插入到原字符序列的指定位置
*/
@Test
public voidtest2() {
StringBuffer sb = newStringBuffer("HelloWorld");
sb.insert(5, "16546546958");//从第五位开始
System.out.println(sb);
}
Delete方法
从该系列中删除指定的位置的字符
/**
*delete:删除字符序列,从开始位置删除到结束位置(不包含结束位置)
*/
@Test
public voidtest3() {
StringBuffer sb = newStringBuffer("HelloWorld");
sb.delete(0, 5);
System.out.println(sb);
}
Replace方法
替换该序列中指定位置的字符串
/**
*replace字符序列的替换:从开始位置到结束位置,替换为指定的字符序列
*/
@Test
public voidtest4() {
StringBuffer sb = newStringBuffer("HelloWorld");
sb.replace(0, 5, "46546476546");
System.out.println(sb);
}
Substring方法
字符串截取,返回一个替换好的String值
/**-
*subString:字符串截取
*/
@Test
public voidtest5() {
StringBuffer sb = newStringBuffer("HelloWorld");
String str = sb.substring(0, 5);
System.out.println(sb);
}
Reverse方法
反转该字符序列
/**
*reverse:字符序列翻转
*/
@Test
public voidtest6() {
StringBuffer sb = newStringBuffer("HelloWorld");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
System.out.println(sb.toString());
}
2542

被折叠的 条评论
为什么被折叠?



