詳解Java String類常用方法有哪些
實質是給底層的char數組value賦值
String s1 = new String();
String s2 = new String(“abc”);
String s3 = new String(new char[]{‘a’,‘b’,‘c’});
str.length() 字符串長度本質是底層的char數組的長度
str.isEmpty() 本質是判斷底層char數組長度是否為0
str.charAt(i) 本質是取底層char數組的第i個元素(字符)
str1.equals(str2)本質是比較二者底層char數組的元素是否都相等
str1.compareTo(str2)本質是返回二者底層char數組中第一個不同元素(字符的碼值)之差,如果沒有不同元素,則返回二者底層char數組長度之差。如果返回0,說明二者底層char數組相同。
package com.llg.learnString;import java.util.Arrays;import java.util.Locale;public class Learn01 { //程序的入口 public static void main(String[] args) {String s11 = 'abcdefghijk';System.out.println(s11);//字符串截取 從第3位開始取到最后System.out.println(s11.substring(3));//defghijk//字符串截取 從第3位開始取到第6位最后System.out.println(s11.substring(3, 6));//def//字符串合并拼接 把zzzzz拼接到后面System.out.println(s11.concat('zzzzz'));//abcdefghijkzzzzz//字符串中的字符替換 把b替換為xSystem.out.println(s11.replace(’b’,’x’));//axcdefghijkString s12 = 'a-b-c-def-ghi-jk';//字符串分割 以-分割字符串,返回字符串數組String[] strarr= s12.split('-');System.out.println(Arrays.toString(strarr));//[a, b, c, def, ghi, jk]//轉換為小寫String s13 = 'abc';System.out.println(s13.toUpperCase());//ABC//轉換為大寫String s14 = 'ABC';System.out.println(s14.toLowerCase());//abc//去除首尾空格String s15 = ' a b c def ';System.out.println(s15.trim());//a b c def//toStringString s16 = 'abc';System.out.println(s16.toString());//abc//轉換為字符串String.valueOfSystem.out.println(String.valueOf(true));//trueSystem.out.println(String.valueOf(false));//false }}
編譯器優化
反匯編查看javap -c Learn5.class
到此這篇關于詳解Java String類常用方法有哪些的文章就介紹到這了,更多相關String類常用方法內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: