String類_獲取,判斷,轉換,替換,切割

6.1 Sting類

 

String類適用於描述字符串事物。

那麼它就提供了多個方法對字符串進行操作。

 

常見的操作有哪些?

"abcd"

 

6.1.1.獲取。

         1.1 字符串中的包含的字符數,也就是字符串的長度。

                   intlength():獲取長度。

         1.2 根據位置獲取位置上某個字符。

                   charcharAt(int index):

         1.3 根據字符獲取該字符在字符串中位置。

                   intindexOf(int ch):返回的是ch在字符串中第一次出現的位置。

                   intindexOf(int ch, int fromIndex) :從fromIndex指定位置開始,獲取ch在字符串中出現的位置。

 

                   intindexOf(String str):返回的是str在字符串中第一次出現的位置。

                   intindexOf(String str, int fromIndex) :從fromIndex指定位置開始,獲取str在字符串中出現的位置。

 

                   intlastIndexOf(int ch) :

 

                  

6.1.2.判斷。

         2.1 字符串中是否包含某一個子串

                   booleancontains(str):

                   特殊之處:indexOf(str):可以索引str第一次出現位置,如果返回-1.表示該str不在字符串中存在。

                    所以,也可以用於對指定判斷是否包含。

                   if(str.indexOf("aa")!=-1)

 

                   而且該方法即可以判斷,有可以獲取出現的位置。

 

         2.2 字符中是否有內容。

                   booleanisEmpty(): 原理就是判斷長度是否爲0.

         2.3 字符串是否是以指定內容開頭。

                   booleanstartsWith(str);

         2.4 字符串是否是以指定內容結尾。

                   booleanendsWith(str);

         2.5 判斷字符串內容是否相同。複寫了Object類中的equals方法。

                   booleanequals(str);

         2.6 判斷內容是否相同,並忽略大小寫。

                   booleanequalsIgnoreCase();

        

6.1.3.轉換。

         3.1 將字符數組轉成字符串。

                   構造函數:String(char[])

                                       String(char[],offset,count):將字符數組中的一部分轉成字符串。

 

                   靜態方法:

                                     staticString copyValueOf(char[]);

                                     staticString copyValueOf(char[] data, int offset, int count)

 

                                     staticString valueOf(char[]):

 

                  

         3.2 將字符串轉成字符數組。**

                   char[]toCharArray():

 

         3.3 將字節數組轉成字符串。

                            String(byte[])

                            String(byte[],offset,count):將字節數組中的一部分轉成字符串。

 

         3.4 將字符串轉成字節數組。

                            byte[]  getBytes():

         3.5 將基本數據類型轉成字符串。

                   staticString valueOf(int)

                   staticString valueOf(double)

 

                   //3+"";//String.valueOf(3);

 

                   特殊:字符串和字節數組在轉換過程中,是可以指定編碼表的。

 

6.1.4.替換

         Stringreplace(oldchar,newchar);

 

6.1.5.切割

         String[]split(regex);

 

6.1.6.子串。獲取字符串中的一部分

         Stringsubstring(begin);

         Stringsubstring(begin,end);

 

6.1.7.轉換,去除空格,比較

         7.1將字符串轉成大寫或則小寫。

                    String toUpperCase();

                    String toLowerCase();

 

         7.2 將字符串兩端的多個空格去除

                   Stringtrim();

 

         7.3 對兩個字符串進行自然順序的比較

                   intcompareTo(string);

 

練習一:String類常見操作

 

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. class StringMethodDemo  
  2. {  
  3.    
  4.          public static void method_7()  
  5.          {  
  6.                    String s = "    Hello Java     ";  
  7.                    sop(s.toLowerCase());  
  8.                    sop(s.toUpperCase());  
  9.                    sop(s.trim());  
  10.    
  11.                    String s1 = "a1c";  
  12.                    String s2 = "aaa";  
  13.    
  14.                    sop(s1.compareTo(s2));  
  15.          }  
  16.          public static void method_sub()  
  17.          {  
  18.                    String s = "abcdef";  
  19.    
  20.                    sop(s.substring(2));//從指定位置開始到結尾。如果角標不存在,會出現字符串角標越界異常。  
  21.                    sop(s.substring(2,4));//包含頭,不包含尾。s.substring(0,s.length());  
  22.          }  
  23.    
  24.          public static void  method_split()  
  25.          {  
  26.                    String s = "zhagnsa,lisi,wangwu";  
  27.    
  28.                    String[] arr  = s.split(",");  
  29.    
  30.                    for(intx = 0; x<arr.length; x++)  
  31.                    {  
  32.                             sop(arr[x]);  
  33.                    }  
  34.          }  
  35.    
  36.          public static void method_replace()  
  37.          {  
  38.                    String s = "hello java";  
  39.    
  40.                    //String s1 = s.replace('q','n');//如果要替換的字符不存在,返回的還是原串。  
  41.    
  42.    
  43.                    String s1 = s.replace("java","world");  
  44.                    sop("s="+s);  
  45.                    sop("s1="+s1);  
  46.          }  
  47.    
  48.          public static void method_trans()  
  49.          {  
  50.                    char[] arr = {'a','b','c','d','e','f'};  
  51.    
  52.                    String s= new String(arr,1,3);  
  53.    
  54.                    sop("s="+s);  
  55.    
  56.                    String s1 = "zxcvbnm";  
  57.    
  58.                    char[] chs = s1.toCharArray();  
  59.    
  60.                    for(intx=0; x<chs.length; x++)  
  61.                    {  
  62.                             sop("ch="+chs[x]);  
  63.                    }  
  64.          }  
  65.          public static void method_is()  
  66.          {  
  67.                    String str = "ArrayDemo.java";  
  68.                     
  69.                    //判斷文件名稱是否是Array單詞開頭。  
  70.                    sop(str.startsWith("Array"));  
  71.                    //判斷文件名稱是否是.java的文件。  
  72.                    sop(str.endsWith(".java"));  
  73.                    //判斷文件中是否包含Demo  
  74.                    sop(str.contains(".java"));  
  75.    
  76.          }  
  77.    
  78.    
  79.          public static void method_get()  
  80.          {  
  81.                    String str = "abcdeakpf";  
  82.    
  83.                    //長度  
  84.                   sop(str.length());  
  85.    
  86.                    //根據索引獲取字符。  
  87.                    sop(str.charAt(4));  
  88. //當訪問到字符串中不存在的角標時會發生StringIndexOutOfBoundsException。  
  89.    
  90.                    //根據字符獲取索引  
  91.                    sop(str.indexOf('m',3));//如果沒有找到,返回-1.  
  92.                     
  93.                    //反向索引一個字符出現位置。  
  94.                    sop(str.lastIndexOf("a"));  
  95.                     
  96.          }  
  97.          public static void main(String[] args)  
  98.          {  
  99.                    method_7();  
  100. //               method_trans();  
  101. //               method_is();  
  102. //               method_get();  
  103.                    /* 
  104.                    String s1 = "abc"; 
  105.                    String s2 = new String("abc"); 
  106.   
  107.                    String s3 = "abc"; 
  108.                    System.out.println(s1==s2); 
  109.                    System.out.println(s1==s3); 
  110.   
  111.                    */  
  112.          }  
  113.    
  114.          public static void sop(Object obj)  
  115.          {  
  116.                    System.out.println(obj);  
  117.          }  
  118. }  


 

練習二:靈活運用String的常見操作

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. /* 
  2. 1,模擬一個trim方法,去除字符串兩端的空格。 
  3.          思路: 
  4.          1,判斷字符串第一個位置是否是空格,如果是繼續向下判斷,直到不是空格爲止。 
  5.                    結尾處判斷空格也是如此。 
  6.          2,當開始和結尾都判斷到不是空格時,就是要獲取的字符串。 
  7.   
  8.   
  9.   
  10. 2,將一個字符串進行反轉。將字符串中指定部分進行反轉,"abcdefg";abfedcg 
  11.          思路: 
  12.          1,曾經學習過對數組的元素進行反轉。 
  13.          2,將字符串變成數組,對數組反轉。 
  14.          3,將反轉後的數組變成字符串。 
  15.          4,只要將或反轉的部分的開始和結束位置作爲參數傳遞即可。 
  16.   
  17.   
  18. */  
  19.    
  20. class StringTest  
  21. {  
  22.    
  23.          public static void sop(String str)  
  24.          {  
  25.                    System.out.println(str);  
  26.          }  
  27.          public static void main(String[] args)  
  28.          {  
  29.                    String s = "      ab cd      ";  
  30.    
  31.                    sop("("+s+")");  
  32. //               s= myTrim(s);  
  33. //               sop("("+s+")");  
  34.    
  35.                    sop("("+reverseString(s)+")");  
  36.                     
  37.          }  
  38.    
  39.    
  40.          //將字符串反轉。  
  41.          /* 
  42.          思路: 
  43.          1,將字符串變成數組。 
  44.          2,對數組反轉。 
  45.          3,將數組變成字符串。 
  46.          */  
  47.    
  48.          public static String reverseString(String s,int start,int end)  
  49.          {  
  50.                    //字符串變數組。  
  51.                    char[] chs = s.toCharArray();  
  52.    
  53.                    //反轉數組。  
  54.                    reverse(chs,start,end);  
  55.    
  56.                    //將數組變成字符串。  
  57.                    return new String(chs);  
  58.          }  
  59.          public static String reverseString(String s)  
  60.          {  
  61.                    return reverseString(s,0,s.length());  
  62.                     
  63.          }  
  64.    
  65.          private static void reverse(char[] arr,int x,int y)  
  66.          {  
  67.                    for(int start=x,end=y-1; start<end ; start++,end--)  
  68.                    {  
  69.                             swap(arr,start,end);  
  70.                    }  
  71.          }  
  72.          private static void swap(char[] arr,int x,int y)  
  73.          {  
  74.                    char temp = arr[x];  
  75.                    arr[x]= arr[y];  
  76.                    arr[y]= temp;  
  77.          }  
  78.    
  79.          //去除字符串兩端空格。  
  80.          public static String myTrim(String str)  
  81.          {  
  82.                    int start = 0,end = str.length()-1;  
  83.    
  84.                    while(start<=end&& str.charAt(start)==' ')  
  85.                             start++;  
  86.    
  87.                    while(start<=end&& str.charAt(end)==' ')  
  88.                             end--;  
  89.    
  90.                    return str.substring(start,end+1);  
  91.          }  
  92. }  


練習三:獲取一個字符串在另一個字符串中出現的次數

 

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. /* 
  2. 3,獲取一個字符串在另一個字符串中出現的次數。 
  3.          "abkkcdkkefkkskk" 
  4.   
  5.          思路: 
  6.          1,定義個計數器。 
  7.          2,獲取kk第一次出現的位置。 
  8.          3,從第一次出現位置後剩餘的字符串中繼續獲取kk出現的位置。 
  9.                    每獲取一次就計數一次。 
  10.          4,當獲取不到時,計數完成。 
  11. */  
  12.    
  13. class StringTest2  
  14. {         
  15.          /* 
  16.          方法一 
  17.          */  
  18.    
  19.          public static int getSubCount(String str,String key)  
  20.          {  
  21.                    int count = 0;  
  22.                    int index = 0;  
  23.    
  24.                    while((index=str.indexOf(key))!=-1)  
  25.                    {  
  26.                             sop("str="+str);  
  27.                             str= str.substring(index+key.length());  
  28.    
  29.                             count++;   
  30.                    }  
  31.                    return count;  
  32.          }  
  33.    
  34.          /* 
  35.          方法二 
  36.          */  
  37.          public static int getSubCount_2(String str,String key)  
  38.          {  
  39.                    int count = 0;  
  40.                    int index = 0;  
  41.    
  42.                    while((index=str.indexOf(key,index))!=-1)  
  43.                    {  
  44.                             sop("index="+index);  
  45.                             index= index + key.length();  
  46.    
  47.                             count++;  
  48.                    }  
  49.                    return count;  
  50.          }  
  51.    
  52.          public static void main(String[] args)  
  53.          {  
  54.                    String str = "kkabkkcdkkefkks";  
  55.    
  56.                    ///sop("count====="+str.split("kk").length);split()不建議使用。  
  57.    
  58.                    sop("count="+getSubCount_2(str,"kk"));  
  59.          }  
  60.    
  61.          public static void sop(String str)  
  62.          {  
  63.                    System.out.println(str);  
  64.          }  
  65. }  


 

練習四:獲取兩個字符串中最大相同子串。

 

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. /* 
  2. 4.獲取兩個字符串中最大相同子串。第一個動作:將短的那個串進行長度一次遞減的子串打印。 
  3.          "abcwerthelloyuiodef" 
  4.          "cvhellobnm" 
  5.          思路: 
  6.                    1,將短的那個子串按照長度遞減的方式獲取到。 
  7.                    2,將每獲取到的子串去長串中判斷是否包含, 
  8.                             如果包含,已經找到!。 
  9. */  
  10. class StringTest3  
  11. {  
  12.          public static String getMaxSubString(String s1,String s2)  
  13.          {   
  14.    
  15.                    String max = "",min = "";  
  16.    
  17.                    max= (s1.length()>s2.length())?s1: s2;  
  18.    
  19.                    min= (max==s1)?s2: s1;  
  20.                     
  21. //               sop("max="+max+"...min="+min);  
  22.                    for(int x=0; x<min.length(); x++)  
  23.                    {  
  24.                             for(int y=0,z=min.length()-x; z!=min.length()+1; y++,z++)  
  25.                             {  
  26.                                      String temp = min.substring(y,z);  
  27.                                       
  28.                                      sop(temp);  
  29.                                      if(max.contains(temp))//if(s1.indexOf(temp)!=-1)  
  30.                                                return temp;  
  31.                             }  
  32.                    }  
  33.                    return "";  
  34.          }  
  35.    
  36.    
  37.          public static void main(String[] args)  
  38.          {  
  39.                    String s1 = "ab";  
  40.                    String s2 = "cvhellobnm";  
  41.                    sop(getMaxSubString(s2,s1));  
  42.          }  
  43.    
  44.          public static void sop(String str)  
  45.          {  
  46.                    System.out.println(str);  
  47.          }  
  48. }  


 

6.1.8  StringBuffer是字符串緩衝區

 

StringBuffer是一個容器。

特點:

1,長度是可變化的。

2,可以字節操作多個數據類型。

3,最終會通過toString方法變成字符串。

 

C create U update R read D delete

 

1,存儲。

         StringBufferappend():將指定數據作爲參數添加到已有數據結尾處。

         StringBufferinsert(index,數據):可以將數據插入到指定index位置。

 

2,刪除。

         StringBufferdelete(start,end):刪除緩衝區中的數據,包含start,不包含end。

         StringBufferdeleteCharAt(index):刪除指定位置的字符。

        

3,獲取。

         charcharAt(int index)

         intindexOf(String str)

         intlastIndexOf(String str)

         intlength()

         Stringsubstring(int start, int end)

 

4,修改。

         StringBufferreplace(start,end,string);

         voidsetCharAt(int index, char ch) ;

 

 

5,反轉。

         StringBufferreverse();

 

6,

         將緩衝區中指定數據存儲到指定字符數組中。

         voidgetChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

 

        

JDK1.5 版本之後出現了StringBuilder.

 

StringBuffer是線程同步。

StringBuilder是線程不同步。

 

以後開發,建議使用StringBuilder

 

升級三個因素:

1,提高效率。

2,簡化書寫。

3,提高安全性。

 

練習五:StringBuffer操作的練習

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. class Demo  
  2. {  
  3. }  
  4.    
  5. class StringBufferDemo  
  6. {  
  7.          public static void main(String[] args)  
  8.          {  
  9.                    //method_update();  
  10.    
  11.                    StringBuilder sb = new StringBuilder("abcdef");  
  12.           
  13.                    char[] chs = new char[6];  
  14.    
  15.                    sb.getChars(1,4,chs,1);//將  
  16.    
  17.                    for(int x=0; x<chs.length; x++)  
  18.                    {  
  19.                             sop("chs["+x+"]="+chs[x]+";");  
  20.                    }  
  21.    
  22.                    draw(3,6);  
  23.                    draw(8,9);  
  24.    
  25. //               StringBuilder sb1 = new StringBuilder();  
  26. //               sb1.append(newDemo()).append(new Demo());  
  27. //               sop("sb1="+sb1);  
  28.          }  
  29.          public static void method_update()  
  30.          {  
  31.                    StringBuffer sb  = newStringBuffer("abcde");  
  32.    
  33. //               sb.replace(1,4,"java");  
  34.                    sb.setCharAt(2,'k');  
  35.    
  36.                    sop(sb.toString());  
  37.           
  38.          }  
  39.          public static void method_del()  
  40.          {  
  41.                    StringBuffer sb  = newStringBuffer("abcde");  
  42.                    
  43. //               sb.delete(1,3);  
  44.                    //清空緩衝區。  
  45.                    //sb.delete(0,sb.length());  
  46.    
  47.                    //sb.delete(2,3);  
  48.                    sb.deleteCharAt(2);  
  49.    
  50.                    sop(sb.toString());  
  51.          }  
  52.    
  53.          public static void method_add()  
  54.          {  
  55.                    StringBuffer sb = new StringBuffer();  
  56.    
  57.                    //sb.append("abc").append(true).append(34);  
  58. //               StringBuffer sb1 = sb.append(34);  
  59. //               sop("sb==sb1:"+(sb==sb1));  
  60.    
  61.                    sb.insert(1,"qq");  
  62.                    sop(sb.toString());//abctrue34  
  63.                    //sop(sb1.toString());  
  64.    
  65.                     
  66.          }  
  67.    
  68.           
  69.          public static void sop(String str)  
  70.          {  
  71.                    System.out.println(str);  
  72.          }  
  73.           
  74.          public static void draw(int row,int col)  
  75.          {  
  76.                    StringBuilder sb = new StringBuilder();  
  77.                    for(int x=0; x<row; x++)  
  78.                    {  
  79.                             for(int y=0; y<col; y++)  
  80.                             {  
  81.                                      sb.append("*");  
  82.                             }  
  83.                             sb.append("\r\n");  
  84.                    }  
  85.    
  86.                    sop(sb.toString());  
  87.          }  
  88.    
  89. }  


 

6.1.9基本數據類型對象包裝類。

 

byte Byte

short         short

int              Integer

long          Long

boolean   Boolean

float           Float

double      Double

char          Character

 

 

 

基本數據類型對象包裝類的最常見作用,

就是用於基本數據類型和字符串類型之間做轉換

 

基本數據類型轉成字符串

 

         基本數據類型+""

 

         基本數據類型.toString(基本數據類型值);

 

         如:Integer.toString(34);//將34整數變成"34";

 

 

字符串轉成基本數據類型

 

         xxxa = Xxx.parseXxx(String);

 

         inta = Integer.parseInt("123");

 

         doubleb = Double.parseDouble("12.23");

 

         booleanb = Boolean.parseBoolean("true");

 

         Integeri = new Integer("123");

 

         intnum = i.intValue();

 

十進制轉成其他進制。

         toBinaryString();

         toHexString();

         toOctalString();

 

 

其他進制轉成十進制。

         parseInt(string,radix);

 

練習六:基本數據類型操作

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. class IntegerDemo  
  2. {  
  3.          public static void sop(String str)  
  4.          {  
  5.                    System.out.println(str);  
  6.          }  
  7.           
  8.          public static void main(String[] args)  
  9.          {  
  10.                    //整數類型的最大值。  
  11.                    //判斷數據是否超出最大值  
  12.                    //sop("intmax :"+Integer.MAX_VALUE);  
  13.    
  14. //               將一個字符串轉成整數。  
  15.    
  16.                    int num = Integer.parseInt("123");//必須傳入數字格式的字符串。  
  17.                    //long x = Long.parseLong("123");  
  18.    
  19. //               sop("num="+(num+4));  
  20.    
  21. //               sop(Integer.toBinaryString(-6));  
  22. //               sop(Integer.toHexString(60));  
  23.    
  24.                    int x = Integer.parseInt("3c",16);  
  25.    
  26.                    sop("x="+x);  
  27.    
  28.    
  29.          }  
  30. }  


 

6.1.10JDK1.5版本以後出現的新特性,基本數據類型自動裝箱、拆箱

 

練習六:基本數據類型的自動拆箱,裝箱

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. class IntegerDemo1  
  2. {  
  3.          public static void main(String[] args)  
  4.          {  
  5.                     
  6. //               Integer x = new Integer(4);  
  7.    
  8.                    Integer x = 4;//自動裝箱。//new Integer(4)  
  9.    
  10.                    x= x + 2;//x+2:x 進行自動拆箱。變成成了int類型。和2進行加法運算。  
  11.                                                //再將和進行裝箱賦給x。  
  12.                    //x的拆箱過程    x.intValue()    
  13.    
  14.                    Integer m = 128;  
  15.                    Integer n = 128;  
  16.    
  17.                    sop("m==n:"+(m==n));  
  18.    
  19.                    Integer a = 127;  
  20.                    Integer b = 127;  
  21.    
  22.                    sop("a==b:"+(a==b));//結果爲true。因爲a和b指向了同一個Integer對象。  
  23.                                                         //因爲當數值在byte範圍內容,對於新特性,如果該數值已經存在,則不會在開闢新的空間。  
  24.          }  
  25.    
  26.          public static void method()  
  27.          {  
  28.                    Integer x = new Integer("123");  
  29.    
  30.                    Integer y = new Integer(123);  
  31.     
  32.                    sop("x==y:"+(x==y));  
  33.                    sop("x.equals(y):"+x.equals(y));  
  34.          }  
  35.    
  36.          public static void sop(String str)  
  37.          {  
  38.                    System.out.println(str);  
  39.          }  
  40.           
  41. }  
發佈了32 篇原創文章 · 獲贊 13 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章