學習總結 String類常用API

2021-06-20 10:54:07 字數 1526 閱讀 5464

建立字串物件

string  students = "小明";  //尋找已建字面量

string students1 = new string("小明");   //另闢空間,建立新的字面量

system.out.println(students.equals(students1));  //輸出為false

獲取字串的長度

string he = "hello,my name is dahai!";

system.out.println(he.length());   //輸出結果為23 ,包含在字串內的標點和空格也計算在內

連線字串

格式1:string1.concat(string2);  //返回乙個新的字串,新字串為string1後面新增上string2

string string1 = "hello";

string string2 = ",my name is dahai!";

system.out.println(string1.concat(string2));  

格式2:system.out.println("hello".concat(",my name is dahai!"));  //可以直接通過字串字面量呼叫concat()方法

格式3:system.out.println("hello"+",my name"+" is dahai!"); //當+用在字串中間時,意思是將多個字串合併在一起生成乙個新的字串

以上輸出結果皆為hello,my name is dahai!

字元陣列與字串之間的相互轉化

字元陣列轉化為字串:

char lovearray = ;

string lovearray1 = new string(lovearray);

system.out.println(lovearray1);    //輸出結果為iloveyou

字串轉化為字元陣列:

string lovearray = "iloveyou";

char lovearray1 = lovearray.tochararray();  //字元陣列為;空格也算乙個字元

操縱乙個字串中的字元

通過索引獲得乙個字元或字串:

string abc = "abcdefghigklmn";

char a = abc.atchar(6);  //字串中第7個字元   輸出為g

string b = abc.substring(7,13);  //字串中第8到第13字元但不包括第13個  輸出為higkl

string c = abc.substring(9);   //字串中第8個字元到最後的字元  輸出為higklmn

操縱字串的其他方法

總結String類常用方法

public class test 1.獲取字串長度 system.out.println str.length 輸出62.判斷字串是否一致 區分大小寫 system.out.println str.equals abcd 輸出false3.判斷字串是否一致 不區分大小寫 system.out.pr...

總結String類常用方法

public class test string str abuiugba system.out.println str.indexof a system.out.println str.lastindexof a 從右向左數a的位置 a還是正常順序的第乙個a system.out.println ...

String類常用操作總結

indexof ch 返回字元所在位置索引下標 system.out.println file.indexof indexof str 返回字元所在位置索引下標 system.out.println file.indexof j 0 system.out.println file.indexof j...