Java基礎 String

String類

  • 字符串是一個特殊的對象。正則表達式

  • 字符串一旦初始化就不能夠被改變。數組

 

 String s="abc";//建立一個字符串對象在常量池中
 
 String s1=new String("abc");//建立了兩個對象,一個new字符串對象在堆內存中。類比new一個對象的內存圖

特色:函數

  1. 字符串對象一旦被初始化就不會改變。spa

  2. 字符串常量池沒有就創建;池中有,直接使用。共享對象

 

String構造函數內存

主要幾個String構造函數字符串

 String(byte[] bytes){}//字節型
 String(byte[] bytes,int offset,int length){}
 String(char[] arr){}//字符數組
 String(char[] arr,int offset,int count){}

 

常見功能

獲取get

一、獲取字符串中字符的個數(長度)string

 int  length();

二、根據位置獲取字符it

 char  charAt(int index);

三、根據字符(字符串)獲取字符串中第一次出現的位置。從前日後查

 1. int  indexOf(int ch);
 2. int  indexOf(int ch,int fromIndex); //從指定位置對ch進行查找
 3. int  indexOf(String str);
 4. int  indexOf(String str,int fromIndex);

四、根據字符(字符串)獲取字符串中第一次出現的位置。從後往前查

 1. int  lastIndexOf(int ch);
 2. int  lastIndexOf(int ch,int fromIndex);
 3. int  lastIndexOf(String str);
 4. int  lastIndexOf(String str,int fromIndex);

五、獲取字符串中一部分字符串,子串

 String substring(int beginIndex, int endIndex);//左閉右開。(要begin不要end)
 String substring(int beginIdex);

 

轉換

一、將字符串轉換成字符串數組(切割)

 String[] split(String regex);//涉及到正則表達式

二、將字符串轉換成字符(char)數組

 char[] toCharArray();

三、將字符串轉換成字節數組

 byte[] getBytes();

四、將字符串中的字母轉換成大小寫

 String toUpperCase();//大寫
 String toLowerCase();//小寫

五、將字符串中的內容進行替換

 String replace(char oldChar,char nowChar);
 String replace(String s1,String s2);

六、將字符串兩端空格去除

 String trim();

七、將字符串進行鏈接

 String concat(String str);

 

判斷

一、兩個字符串內容是否相同

 boolean equals(Object obj);
 boolean equalsIgnoreCase(String str); //忽略大小寫比較字符串內容

二、字符串中是否包含指定字符串

 boolean contains(String str);

三、字符串是否以指定字符串開頭,或結尾

 boolean startsWith(String str);//開頭
 boolean endsWith(String str);//結尾

 

比較

按字典順序比較兩個字符串

 int compareTo(String anotherString) 

 

字符串對象的規範化表示

 String intern();

事例:

 String t=new String("abc");//new一個String對象,在堆內存中
 t.intern();//將"abc"添加進字符串池中
相關文章
相關標籤/搜索