1. 程式人生 > >javaSE三個特殊的類 -- String類&String類面試題

javaSE三個特殊的類 -- String類&String類面試題

String類

String類

  • String的兩種例項化方式

            直接賦值(用的最多)

                String str=“Hello”;

            傳統方法,例項化物件

                String str=new String("Hello");

  • 字串相等比較

            str.equals(str1);   //比較的是內容

            public boolean equals(String str1)

  • 字串常量是String類的匿名物件

            tips:在指定內容比較時,將指定內容(字串常量)寫在前面,避免NullPointException

          

 

面試題:請解釋String類“==”與“equals”的區別

  1. “==”:進行的是數值比較,比較的是兩個字串物件的記憶體地址數值

  2. equals()”:可以進行字串內容的比較

  • String採用共享設計模式   在JVM底層自動維護一個字串物件池(物件陣列)。

      如果採用直接賦值的模式進行String類的物件例項化操作,此物件將自動儲存到物件池中,如果有,直接引用,如果沒有,開闢新的空間將其儲存到物件池中共下次使用;

      物件池就是一個物件陣列目的就是減少記憶體的開銷

      字串手工入池操作:

      public native String intern();

範例:


  
  1. // 該字串常量並沒有儲存在物件池之中
  2. String str1 = new String( "hello");
  3. String str2 = "hello" ;
  4. System.out.println(str1 == str2); // false
  5. ----------------------------------
  6. ----------------------------------
  7. // 使用手動入池操作
  8. String str1 = new String( "hello").intern() ;
  9. String str2 = "hello" ;
  10. System.out.println(str1 == str2); // true

面試題:請解釋String類中兩種物件例項化的區別

  1. 直接賦值 就會自動採用共享模式,只會開闢一塊堆記憶體空間,並且該字串物件可以自動儲存在物件池中以供下次使用。

  2. 構造方法 就會開闢兩塊堆記憶體空間並且其中一塊堆記憶體將成為垃圾空間,不會自動儲存在物件池中,可以使用intern()方法手工入池。

        

  • 字串常量不可變更

            字串常量一旦定義不可改變

範例:觀察如下程式碼


  
  1. String str = "hello" ;
  2. str = str + " world" ;
  3. str += "!!!" ;
  4. System.out.println(str); // hello world!!!

以上字串變更是字串物件變更非字串常量

記憶體中的字串修改如下圖所示:

可以發現字串上沒有發生變化,但是字串物件的引用一直在改變,並且形成了大量垃圾空間。正是因為 String的特點,所以如下程式碼不應該在你的開發中出現:


  
  1. String str = "hello" ;
  2. for( int x = 0 ; x< 1000 ; x++) {
  3. str += x ;
  4. }
  5. System.out.println(str)

如果有很多使用者都使用了同樣的操作,那麼產生的垃圾數量就相當可觀了。

字串使用原則

  1. 字串使用就採用直接賦值

  2. 字串比較就使用equals()實現

  3. 字串不要改變太多,防止產生過多垃圾空間

  • 字元與字串  String <-> char[]

            1. 字元陣列 char[]-> String

                功能:將字元陣列中所有內容變為字串

                建構函式為:public String ( char[] value1 ) ;

                功能:將部分字元陣列中的內容變為字串

                建構函式為:public String ( char[] value1, int offset, int count ) ;

            2. String -> char

                功能:將字串按照索引轉為單個字元

                普通函式:public char charAt ( int index ) ;

                如果使用charAt()方法超出了字串長度,則會產生StringIndexOutOfBoundsException異常

            3. String -> char[]     *** 重點 ***

                功能:將字串轉為字元陣列

                普通函式:public char[] toCharArray( ) ;

範例:


  
  1. public class Test{
  2. public static void main(String[] args){
  3. String str = "helloworld" ;
  4. // 將字串變為字元陣列
  5. char[] data = str.toCharArray() ;
  6. for ( int i = 0; i < data.length; i++) {
  7. data[i] -= 32 ;
  8. System.out.print(data[i]+ "、");
  9. }
  10. // 字元陣列轉為字串
  11. System.out.println( new String(data)); // 全部轉換
  12. System.out.println( new String(data, 5, 5)); // 部分轉換
  13. }
  14. }
  15. //輸出
  16. //H、E、L、L、O、W、O、R、L、D、HELLOWORLD
  17. //WORLD

 

面試題:判斷給定字串是否由數字組成?  *** 重要 *** 


  
  1. public class Test{
  2. public static void main (String[] args){
  3. String str= "123";
  4. boolean a=MyAdjust(str);
  5. if(a== true){
  6. System.out.println( "字串是由數字組成!");
  7. }
  8. else{
  9. System.out.println( "字串中含有非數字成員!");
  10. }
  11. }
  12. public static boolean MyAdjust(String str){
  13. //將字串轉換為字串陣列
  14. char[] data=str.toCharArray();
  15. for( int i= 0;i<data.length;i++){
  16. if(data[i]< '0'||data[i]> '9'){
  17. return false;
  18. }
  19. }
  20. return true;
  21. }
  22. }

 

  • 位元組與字串    

            功能:位元組陣列轉為字串   byte[]  ->  String

            String構造方法:public String(byte[] bytes)

            功能:字串轉為位元組陣列   String  ->  byte[]   *** 非常重要 ***

            String普通方法:public byte[] getBytes(String charset);按照指定編碼轉為位元組陣列

            亂碼的產生(編解碼不一致,順序不一致)

範例:


  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str = "helloword";
  4. byte[] data = str.getBytes();
  5. for ( int i = 0; i < data.length; i++) {
  6. data[i] -= 32;
  7. System.out.print(data[i]+ " ,");
  8. }
  9. System.out.println( new String(data));
  10. }
  11. }
  12. //編譯結果如下:
  13. //72 ,69 ,76 ,76 ,79 ,87 ,79 ,82 ,68 ,HELLOWORD
  • 字串比較

            不區分大小寫的比較方法  ( 比如輸入驗證碼 )

            public boolean equalsIgnoreCase(String anotherString)

範例:


  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str1= "helloword";
  4. String str2= "HELLOWORD";
  5. System.out.println(str1.equals(str2));
  6. System.out.println(str1.equalsIgnoreCase(str2));
  7. }
  8. }
  9. //編譯結果如下:
  10. //false
  11. //true
  •  比較兩個字串大小關係   *** 重要 ***

            public int compareTo(String anotherString) ( 只需要比到第一個不同的字元即可 )

            1. >0 : 表示本字串大於目標字串

            2. =0 : 表示兩者相等

            3. <0 : 表示本字串小於目標字串

範例:


  
  1. public class Test {
  2. public static void main(String[] args) {
  3. System.out.println( "A".compareTo( "a"));
  4. System.out.println( "a".compareTo( "A"));
  5. System.out.println( "A".compareTo( "A"));
  6. System.out.println( "AB".compareTo( "AC"));
  7. System.out.println( "代".compareTo( "李"));
  8. }
  9. }
  10. //編譯結果如下:
  11. //-32
  12. //32
  13. //0
  14. //1
  15. //-6251
  • 字串查詢

            從一個完整的字串當中判斷一個字串是否存在   ***  重要  ***

            public Boolean contains(Sting str);

範例:


  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= "Helloworld";
  4. System. out.println(str.contains( "world"));
  5. }
  6. }
  7. //編譯結果如下
  8. //true

            判斷是否以指定字串開頭

            public boolean startWith(String prefix)

            public boolean startWith(String prefix,int toffset)toffset(偏移量)

            判斷是否以指定字串結尾

            public boolean endsWith(String suffix)

範例:


  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= "Helloworld";
  4. System.out.println(str.startsWith( "H"));
  5. System.out.println(str.startsWith( "l", 2));
  6. System.out.println(str.startsWith( "e"));
  7. System.out.println(str.endsWith( "d"));
  8. }
  9. }
  10. //編譯結果如下:
  11. //true
  12. //true
  13. //false
  14. //true
  • 字串替換

            public String replaceAll(String regex,String replacement)

            將目標字串全部替換

            str.replaceAll(“l”,“_”):將str中的所有 "l" 換成  "_"

            public String replaceFirst(String regex,String replacement)(替換首個)

範例:


  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= "helloworld";
  4. System.out.println(str.replaceAll( "l", "*"));
  5. System.out.println(str.replaceFirst( "l", "*"));
  6. }
  7. }
  8. //編譯結果如下:
  9. //he**owor*d
  10. //he*loworld
  • 字串拆分    ***  重要  ***

            將字串全部拆分

            public String[] split(String regex)

            將字串拆分成陣列長度為limit的字串陣列

            public String[] split(String regex,int limit)

範例:


  
  1. public class Test{
  2. public static void main(String[] args){
  3. String str= "hello world hello bit and you";
  4. String[] result=str.split( " ", 2);
  5. //String[] result=str.split(" ",3);
  6. //String[] result=str.split(" ",4);
  7. //String[] result=str.split(" ",5);
  8. for(String s:result){
  9. System.out.print(s+ " , ");
  10. }
  11. }
  12. }
  13. //編譯結果如下:
  14. //hello ,world hello bit and you
  15. //hello ,world, hello bit and you
  16. //hello ,world ,hello ,bit and you
  17. //hello ,world ,hello, bit, and you

            特殊字元需要轉義後拆分  \\

            eg:\\.

範例:  實現多次拆分   *** 重要  ***


  
  1. public class Test{
  2. public static void main(String[] args){
  3. String str= "yum:21|hsd:176";
  4. String[] temp=str.split( "\\|");
  5. for( int i= 0;i<temp.length;i++){
  6. String name=temp[i].split( ":")[ 0];
  7. String age=temp[i].split( ":")[ 1];
  8. System.out.println( "姓名為:"+name);
  9. System.out.println( "年齡為:"+age);
  10. }
  11. }
  12. }
  • 字串擷取   *** 重要 ***

            從指定索引擷取到結尾

            public Srting substring (int beginIndex)

            從指定索引截部分內容  左閉右開  [  )

            public String substring(int beginIndex,int endIndex)

範例:


  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= "helloworld";
  4. System.out.println(str.substring( 5));
  5. System.out.println(str.substring( 0, 5));
  6. }
  7. }
  8. //world
  9. //hello
  • 字串其他操作方法

            去除字串左右空格,並且保留中間空格

            public String trim() 可以與replaceAll配合使用  “   hello   world   ”

範例:


  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= " hello world ";
  4. System.out.println( "["+str+ "]");
  5. System.out.println( "["+str.trim()+ "]");
  6. }
  7. }
  8. //[ hello world ]
  9. //[hello world]

            字串轉大小寫(全部大小寫)(兩個函式只是在字母之間進行大小寫轉換)

            public String toUpperCase() //轉大寫

            public String toLowerCase() //轉小寫          

範例:


  
  1. public class Test {
  2. public

    相關推薦

    javaSE特殊 -- String&amp;String試題

    String類 String類 String的兩種例項化方式             直接賦值(用的最多)     

    javaSE特殊 -- String

    String類 String類 String的兩種例項化方式             直接賦值(用的最多)                 String str=“Hello”;             傳統方法,例項化物件                

    javaSE特殊 -- String&String試題

    String類 String類 String的兩種例項化方式             直接賦值(用的最多)                 String str=“Hello”;             傳

    JavaSE特殊---String

    String類 String類的兩種例項化方式 a.直接賦值 (推薦使用此方式) String str = “Hello world”; b.通過構造方法例項化String類物件 String str = new String(“Hello world”)

    JavaSE——特殊(2)

    String類(下) 1.字串查詢 從一個完整的字串之中可以判斷指定內容是否存在,查詢方法如下: No. 方法名稱 型別 描述 1. public boolean

    JavaSE特殊(一、String

    String類的兩種例項化方式  (1)、直接賦值: public class Test1{ public static void main(String[] args) { String str = "hello"; // str是一個物件,

    java中特殊------String、Object、包裝

    1.String類 1.1 String類的兩種例項化方式 直接賦值 String str = "hello" 通過構造方法例項化String類 String str = new String("hello") 1.2 字串相等比較(內容) public bo

    Java-特殊

    1.String類 1.1String的兩種例項化方式 a.直接賦值 String str=“hello”; b.通過構造方法例項化String物件 1.2字串相等比較 str.equals(str1) public boolean equals(String 

    [CSP初賽] 組合數學的技巧以及從另一方面思考組合問題

    也不知道老師講不講 話說好久沒有水部落格了,看了一點$python$然後就去搞文化課了 正好網課講到組合數學,然後覺得還蠻難的(其實是我變菜了),就想到了以前的$csp$的組合數學基礎 果然被我找到了,**插板法,插空法和捆綁法** ~~就從數學作業裡找例題吧~~ 最後還有關於**四

    JAVA-初步認識-第二章-自動型提升&amp;強制型轉換

    錯誤 http .com com 算術 都是 字符 java 原因 一. 深入理解變量 在之前的講解中,我們談論的都是定義不同類型的變量時要註意的問題。這一節中,我們將變量投入運算,探索在運算過程中,應該遵守的規則。 在這裏對上一節《變量的基本演示》做一個小結,主要有三點。

    浮點型的特殊值 Double.NEGATIVE_INFINITY 負無窮 Double.POSITIVE_INFINITY 正無窮 Double.NaN 非值

    浮點型的三個特殊值 Double.NEGATIVE_INFINITY 負無窮 Double.POSITIVE_INFINITY 正無窮 Double.NaN 非值 public void testFun1() { //無窮 --一個浮點型(無論是基本型別還是

    Ruby學習之File 和方法&amp;Dir 和方法

    File 表示一個連線到普通檔案的 stdio 物件。open 為普通檔案返回該類的一個例項,來看下它的類方法: 序號 方法 & 描述 1 File::atime( path) 返回 path 的最後訪問時間。

    電子資訊、通訊、電專業將會遇到的試題大全的部分答案

    Setup/hold time是測試晶片對輸入訊號和時鐘訊號之間的時間要求。建立時間是指觸發器的時鐘訊號上升沿到來以前,資料穩定不變的時間。輸入訊號應提前時鐘上升沿(如上升沿有效)T時間到達晶片,這個T就是建立時間-Setup time.如不滿足setup time,這個資料就不能被這一時鐘打入觸發器,只有

    (位運算子)請自己實現兩整數變數的交換 ^的特點 (試題

    int a=10;int b=20;//方式1:借用第三方變數int c;c=a;a=b;b=c;System.out.println("a:"+a+":"+"b:"+b);//方式2:使用位異或實現a=a^b;b=a^b;a=a^b;System.out.println("a:"+a+":"+"b:"+b)

    銀四:螞蟻金服JAVA開發試題及答案之一面(持續更新)

    開發十年,就只剩下這套架構體系了! >>>   

    銀四,2019大廠Android高階工程師試題整理

    開發十年,就只剩下這套架構體系了! >>>   

    關於String的異同點對比介紹

    (1)相同點:                      這三個類String、StringBuffered、StringBuilder都是由final修飾的,所以三者均不可以被繼承。

    JAVA中String,StringBuilder以及StringBuffer之間的區別

    不斷地學習,不斷地填充自己的技術庫,學習Java已經有一段時間了,由一開始的不適應到後來的足以靈活應對,不僅僅取決於老師的精緻講課,還有就是依靠我的學習祕籍:記錄自己的學習筆記。今天給大家分享的技術學習筆記是JAVAString,StringBuilder以及StringBuffer這三個類之間的區別。 &

    javaSE (十六)Runtime、Timer、兩執行緒之間的通訊、及以上執行緒通訊、sleep和wait的區別

    1、Runtime類: runtime類其實是單例模式(見上文)的一個體現,它的構造方法被私有化,可以在程式碼中輸入命令字串控制計算機 程式碼例項: package cn.xinhua; import java.io.IOException; public class Threa

    深入瞭解String,StringBuffer和StringBuilder的異同

    Java提供了三個類,用於處理字串,分別是String、StringBuffer和StringBuilder。其中StringBuilder是jdk1.5才引入的。 這三個類有什麼區別呢?他們的使用場景分別是什麼呢? 本文的程式碼是在jdk12上執行的,jdk12和jdk5,jdk8有很大的區別,特別是Str