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="[email protected]";
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());
}