1. 程式人生 > >Java基礎String的方法

Java基礎String的方法

打印 下標 ase [] 替換字符 類型 字符串長度 src 生成

Java基礎String的方法

字符串類型寫法格式如下:
格式一:
String 變量名稱;
變量名稱=賦值(自定義或傳入的變量值);
格式二:
String 變量名稱=賦值(自定義或傳入的變量值);
在輸出時任何數據類型與字符串進行拼接,結果一般是字符串
 1 public class StringFunc {
 2 
 3     public static void main(String[] args){
 4         //字符串拼接
 5         String str1;
 6         str1 = "hello";
7 String str2 = " world"; 8 System.out.println(str1+str2); 9 //字符串與整數拼接 10 int num = 100; 11 String socers = "得分:"; 12 System.out.println(socers + num); 13 //字符串與對象拼接 14 StringFunc Test = new StringFunc(); 15 System.out.println(socers + Test);
16 //字符串方法總結 17 String str3 = "abcdef"; 18 System.out.println("length: "+str3.length()); //查看字符串長度 19 System.out.println("concat: "+"xxx".concat("a")); //在結尾默認追加字符串 20 System.out.println("replace: "+"aaa".replace("a","z")); //替換字符串種的字符 21 System.out.println("isEmpty: "+"".isEmpty()); //
判斷字符串是否為空 22 System.out.println("substring: "+"abcdef".substring(3)); //從首位移除多少個字符 23 System.out.println("substring: "+"abcdef".substring(2,5)); //從字符哪截取到哪 24 System.out.println("length: "+str3.toUpperCase()); //轉換小寫字母為部大寫 25 System.out.println("length: "+"ABCDEF".toLowerCase()); //轉換大寫字母為小寫 26 System.out.println("startsWith: "+"abcd".startsWith("abc")); //判斷以什麽開頭 27 System.out.println("endsWith: "+"edef".endsWith("def")); //判斷以什麽結尾 28 String[] list = "a,b,c,d".split(","); //字符串根據分隔符轉換成列表的操作 29 System.out.println("split: "+list[0]+" "+list[1]+" "+list[2]+" "+list[3]); //打印上面的列表值 30 //以下僅作了解 31 System.out.println("indexOf: "+str3.indexOf(97)); //輸入對應ASCII碼整數對應字符下標會返回 32 System.out.println("indexOf: "+"abc".indexOf("b")); //判斷字符的下標 33 System.out.println("hashCode: "+"123".hashCode()); //為這個字符串生成哈希值 34 System.out.println("charAt: "+str3.charAt(3)); //返回字符串下表對應的單個字符 35 System.out.println("codePointAt: "+str3.codePointAt(1)); //返回字符串對應位置的ASCII碼 36 System.out.println("codePointBefore: "+str3.codePointBefore(1)); //查看字符串對應位置前一位的ASCII碼 37 System.out.println("codePointCount: "+str3.codePointCount(1,6)); //查看字符串指定下標長度 38 System.out.println("compareTo: "+"z".compareTo("a")); //對比兩個字符串相差多少位(利用ASCII碼運算差值) 39 } 40 }

具體輸出如下:

技術分享圖片

 

Java基礎String的方法