String類

Java通過程序中建立String類可以輕松管理字符串。字符串是一個或多個字符組成的連續(xù)序列,程序需要存儲的大量文字,字符都使用字符串進行表示處理。
Java中定義了String和StringBuffer兩個類來封裝對字符串的各種操作,它們都放到了Java.lang包中,不需要用import java.lang這個語句導入該包就可以直接使用他們。
String類用于比較兩個字符串,查找和抽取串中的字符或字串,進行字符串與其他類型之間的相互轉(zhuǎn)換等。String類對象內(nèi)容一旦初始化就不能再改變,對于String類的每次改變(例如字符串連接等)都會生成一個新的字符串,比較浪費內(nèi)存。
StringBuffer類用于內(nèi)容可以改變的字符串,可以將其他各種類型的數(shù)據(jù)增加,插入到字符串中,也可以轉(zhuǎn)置字符串中原來的內(nèi)容。一旦通過StringBuffer生成了最終想要的字符串,就應該使用StringBuffer.toString()方法將其轉(zhuǎn)換成String類,隨后就可以使用String類的各種方法操縱這個字符串了。StringBuffer每次都改變自身,不生成新的對象,比較節(jié)約內(nèi)存。

String s; 。聲明一個字符串s分配一個內(nèi)存空間,因為沒初始化,所以沒有存入任何對象。s作為局部變量是不會自動初始化的,必須顯式地賦初始值,在用System.out.println(s)時會報錯。

用戶可以通過創(chuàng)建String類來創(chuàng)建字符串,String對象既可以隱式的創(chuàng)建,也可以顯式地創(chuàng)建,具體創(chuàng)建形式取決于字符串在程序中的用法,為了隱式地創(chuàng)建一個字符串,用戶只要將字符串放在程序中,Java則會自動的創(chuàng)建String對象。

String類的兩種實例化方式

1,使用字符串常量直接初始化,String對象名稱="字符串";
String s="有志者事竟成";

2,使用構造方法創(chuàng)建并初始化(public String(String str)),String 對象名稱=new String("字符串");
String s=new String("有志者事竟成");

通過String類實例化方式

class jdjd
{
    public static void main(String args[])
    {
        String str1="Hello";   //直接賦值建立對象str1
        System.out.println("ste1:"+str1);   //輸出
        String str2=new String("有志者事竟成");   //構造方法創(chuàng)建并初始化對象str2
        System.out.println("str2:"+str2);
        String str3="new"+"String";        //采用串聯(lián)方式生成新的字符串str3
        System.out.println("str3:"+str3);
    }
    }
//三種方式都完成了String對象的創(chuàng)建及初始化

String對象也可以先聲明在賦值

String str1;     //聲明字符串對象str1
str1=“hello”;    //字符串對象str1賦值為“hello”。

2,構造方法先聲明在賦值
String sre2 =new String();     構造方法創(chuàng)建一個字符串str2,內(nèi)容為空字符串。等同于String str2=new String(" ");
str2="有志者事竟成";   //字符串對象str2賦值為"有志者事竟成"

String內(nèi)容的比較

方法名稱 類型 描述
public boolean equals(String anObject) 普通 區(qū)分大小寫比較
public boolean equalsIgnoreCase(String anotherString) 普通 不區(qū)分大小寫比較
public int compareTo(String anotherString) 普通 比較字符串大小關系

Java中判斷字符串一致方法有兩種

1,調(diào)用equals(object)方法。
String1.equals(String2),比較當前對象(String1)包含的值與參數(shù)對象(String2)包含的值是否相等,若相等則equals()返回true,否則false,equals()比較時考慮字符中字符大小寫的區(qū)別。**equalslgnoreCase()可以忽略大小寫的進行兩個字符串的比較。

String str1="Hello Java";   //直接賦值實例化對象str1。
Boolean result=str1.equals("Hello Java");       //result=true
Boolean result=str1.equals("Hello java");      //result=false
Boolean result=str1.equalslgnoreCase("Hello java");      //result=true

2,使用運算符==
運算符==比較兩個對象是否引用一個實例。

String str1="Hello";   //直接賦值實例化對象str1
String str2="Hello";   //直接賦值實例化對象str2
Boolean result=(str1==str2);    //result=true
String str3=new String("Hello");    //構造方法賦值
Boolean result2=("str1==str3");      //result=false

解析1,如果說String是一個類,那么str1一定是這個類的對象,對象名稱一定要保存在棧內(nèi)存之中,那么字符串"Hello"一定保存在棧內(nèi)存之中;
2,任何情況下使用關鍵字new都會開辟一個新的堆內(nèi)存空間;
3,String本身是一個類,所以String類的對象是一定可以進行引用傳遞的,引用傳遞的最終結果就是不同的棧內(nèi)存將保存在同一塊堆內(nèi)存空間的地址;
4,棧內(nèi)存像int型數(shù)據(jù),里面保存的是數(shù)值,每一個棧內(nèi)存只能夠保存一塊堆內(nèi)存的物理地址數(shù)值。
"=="是對兩個對象的堆內(nèi)存地址的相等進行判斷;對字符串內(nèi)容判斷使用equals()。

//判斷字符串是否相同
class jdjd
{
    public static void main(String args[])
    {
        String str1="Hello";  //直接賦值
        String str2=new String("Hello");   //構造方法賦值
        String str3=str2;   //引用傳遞
        System.out.println(str1==str2);   //false
        System.out.println(str1==str3);   //false
        System.out.println(str2==str3);   //true
        System.out.println(str1.equals(str2));   //true
        System.out.println(str1.equals(str3));   //true
        System.out.println(str2.equals(str3));   //true
    }
    }

Java中判斷字符串大小
如果希望知道字符串大小情況,需要調(diào)用compareTo()方法
字符串對象小于給定字符串:compareTo()方法返回小于0的值;
字符串對象等于給定字符串:compareTo()方法返回小于0的值;
字符串對象大于給定字符串:compareTo()方法返回大于0的值;
比較是根據(jù)字母順序,嚴格來講是根據(jù)字符的ASCII碼值進行比較的,返回結果是第一個不同字符ASCII碼的差值。

class jdjd
{
    public static void main(String args[])
    {
    String str1="This is a string";   //直接賦值建立對象str1
    String str2=new String("this is a string");  //構造方法建立對象str2
    int result=str1.compareTo("That is another string");   // result=8
    int result1=str1.compareTo("This is a string");  //result=0
    int result2=str1.compareTo(str2);    //resutl=-32
    System.out.println(result);
    System.out.println(result1);
    System.out.println(result2);
    }
    }

字符串常量是String類的匿名對象
任何語言實際上都不會提供字符串類型,但是在Java里面為了簡化用戶開發(fā)難度專門提供了String類和使用“ " ”定義的字符串,但實際上每一個字符串嚴格來講都是String類的匿名對象。
匿名對象特點:沒有名字,而且可以調(diào)用類中相關方法

String str="Hello";
System.out.println(str.equals("Hello"));   //true,字符串對象調(diào)用equals()
System.out.println("Hello".equals(str));    //true,字符串常量調(diào)用equals(),"Hello"是String類的匿名對象。

判斷某一用戶輸入的字符串內(nèi)容是否等于指定的字符串內(nèi)容,若采用字符串對象.equals("內(nèi)容")的方式,如果用戶沒輸入字符串,會出現(xiàn)NullPointerException警告,可以采用"字符串".equals(字符串對象)的方式解決這個問題。

String str=null;    //假設這個字符串由用戶輸入
if(str.equals("Hello"))   //true,字符串對象調(diào)用equals()
{
System.out.println("驗證通過");
}
if("Hello".equals(str))   //equals()可自動處理null問題,正常判斷
{
System.out.println("驗證通過");
}

兩種字符串實例化方式的區(qū)別
實例化字符串對象可以采用兩種方式完成,不同方式在內(nèi)存中呈現(xiàn)的方式不同的分配形式。
1,直接賦值方式
如果采用直接賦值形式,那么就好比將一個字符串的常量賦給了指定的字符串變量,而且每一個字符串都屬于String的匿名對象。 ** String str="Hello";** //直接賦值
以直接賦值方式創(chuàng)建對象str,僅開辟一塊堆內(nèi)存和一塊棧內(nèi)存空間。

2,構造方法實例化
此時會開辟兩塊堆內(nèi)存空間,其中一塊堆內(nèi)存將會成為垃圾,通過構造方法進行的String類對象也無法進入自動入池的操作,即,數(shù)據(jù)無法共享。
在String類中提供了一個方法,可以幫助用戶手工入池。
手工入池:public String intern();

class ffff
{
    public static void main(String args[])
    {
        String str1="Hello";   //直接賦值
        String str2=new String("Hello").intern();   //手工入池
        String str3="Hello";   //直接賦值
        String str4=new String("Hello");   //構造方法賦值
        System.out.println(str1==str2);    //true
        System.out.println(str1==str3);    //true
        System.out.println(str2==str3);    //true
        System.out.println(str1==str4);   //false
    }
}

字符串一旦聲明則不可改變
改變也只會改變String對象的引用。

-----------------------------分割線---------------------------
String類常用方法

方法名稱 類型 描述
public String(char[] value) 構造 將接收到的字符變?yōu)樽址?/td>
public Stringchar[] value,int offset,int count) 構造 將部分字符數(shù)組變?yōu)樽址?/td>
public char charAt(int index) 普通 返回指定索引位置上的字符內(nèi)容
public char[] toCharArray() 普通 將字符串變?yōu)樽址麛?shù)組
//求字符串中的指定字符
public class Main
{
    public static void main(String[] args)
    {
        String str="hellojava";    //直接賦值
        System.out.println(str.charAt(0));   //取出字符串中的第一個字符
        System.out.println(str.charAt(3));   //取出字符串中的第4個字符
    }
}

字符串與字符數(shù)組互相轉(zhuǎn)換

public class Main
{
    public static void main(String[] args)
    {
        String str="hellojava";
        char data[]=str.toCharArray();   //將字符串變?yōu)樽址當?shù)組
        for(int x=0;x<data.length;x++)
        {
            System.out.print(data[x]+" ");
            data[x]-=32;//小寫變大寫(str字符串中的內(nèi)容為小寫字符,同一個小寫的ASCII碼比大寫大32)
        }
        System.out.println();
        System.out.println("將全部字符數(shù)組變?yōu)樽址?"+new String(data));
        //取得部分內(nèi)容的時候需要設置起始點和長度(5為起始點,4為長度)
        System.out.println("將部分字符數(shù)組變?yōu)樽址?"+new String(data,5,4)); 
}
}

字節(jié)與字符串

方法名稱 類型 描述
public String(byte[] bytes) 構造 將全部字節(jié)數(shù)組變?yōu)樽址?/td>
public String(byte[] bytrs,int offset,int length) 構造 將部分字節(jié)數(shù)變?yōu)樽址?/td>
public byte[] getBytes() 普通 將字符串變?yōu)樽止?jié)數(shù)組
public byte[] getBytes(String charsetName)throws UnsupportedEncodingException 普通 將字符串轉(zhuǎn)碼
//字符串與字節(jié)相互轉(zhuǎn)換
public class Main
{
    public static void main(String[] args)
    {
        String str="hellojava";
        byte data[]=str.getBytes();  // 將字符串變?yōu)閎yte數(shù)組
        for(int i=0;i<data.length;i++)
        {
            data[i]-=32;
        }
        System.out.println(new String(data));  //將全部byte數(shù)組變?yōu)樽址?        System.out.println(new String(data,5,4));   //將部分byte數(shù)組變?yōu)樽址?    }
}

字符串查找方法

由一個字符串中若干字符按順序形成的連續(xù)字符片段,就是字符串的子串
從一個指定的字符串之中查找某一個子字符串是否存在操作,稱為字符串查找。查找操作方法如下

方法名稱 類型 描述
public boolean contains(String s) 普通 判斷某一個子字符串是否存在
public int indexOf(String str) 普通 由前向后查找指定子字符串的位置,找不到返回-1
public int indexOf(String str,int fromIndex) 普通 由指定位置查找子字符串位置,找不到返回-1
public int lastIndexOf(String str) 普通 由后向前查找制定字符串位置,找不到返回-1
public int lastIndexOf(String str,int fromIndex) 普通 由指定位置從后向前查找
public boolean startsWith(String prefix) 普通 判斷是否以指定字符串開頭
public boolean startsWith(String prefix,int toffset 普通 從指定位置開始判斷是否以指定字符串開頭
public boolean endsWith(String suffix) 普通 判斷是否以指定字符串結尾
//字符串查找方法
public class Main
{
    public static void main(String[] args)
    {
        String str="**hello$$world##";
        if(str.contains("hello"))   //查找hello是否存在
        {
            System.out.println("內(nèi)容存在,已經(jīng)查到");
        }
        if(str.indexOf("r")!=-1)   //查找hello是否存在
        {
            System.out.println("內(nèi)容存在,字符串位置:"+str.indexOf("r"));
        }
        if(str.indexOf("o",6)!=-1)   //由指定位置開始查找
        {
            System.out.println("內(nèi)容存在,字符串位置:"+str.indexOf("o",6));
        }
        if(str.lastIndexOf("w",12)!=-1)   //由指定位置從后向前開始查找
        {
            System.out.println("內(nèi)容存在,字符串位置:"+str.lastIndexOf("w",12));
        }
        System.out.println(str.startsWith("**"));//判斷字符串的起始內(nèi)容
        System.out.println(str.startsWith("$$",7));   //判斷從索引7位置是否以$$開始
        System.out.println(str.endsWith("##"));   //判斷是否以##結束
        }
        }

字符串替換

方法名稱 類型 描述
public String replaceAll(String regex,String replacement) 普通 字符串全部替換為指定內(nèi)容
public String replaceFirst(String regex,String replacement) 普通 替換掉首個內(nèi)容
//字符串替換方法
public class Main
{
    public static void main(String[] args)
    {
        String str="helloworld";
        System.out.println(str.replaceAll("o","***"));   //所有子串出現(xiàn)的位置都替換
        System.out.println(str.replaceFirst("l","_"));    //替換第一次出現(xiàn)字符子串
    }
    }

字符串截取
從一個字符串中取出里面部分內(nèi)容,即子串。從字符串截取子串方法如下

方法名稱 類型 描述
public String substring(int beginIndex) 普通 由指定位置截取到結尾
public String substring(int beginIndex) 普通 截取指定范圍字符串
//字符串中取子串方法
public class Main
{
    public static void main(String[] args)
    {
        String str="Hellojava";
        System.out.println(str.substring(5));   //截取從指定位置到末尾的子串
        System.out.println(str.substring(0,5));   //截取從指定位置到結束位置子串
    }
    }

字符串拆分
字符串拆分指的是將一個字符串按照指定的字符串regex拆分為字符串,返回一個字符型數(shù)組,regex不作為任何數(shù)組元素的部分返回。操作方法如下

方法名稱 類型 描述
public String[] split(String regex) 普通 按照指定的字符串全拆分
public String[] split(String regex int limit) 普通 將字符串拆分為指定元素個數(shù)的字符數(shù)組
//字符串拆分方法
public class Main
{
    public static void main(String[] args)
    {
        String str="hello world hello java";
        String data[]=str.split(" ");  // 按照空格拆分
        for(int i=0;i<data.length;i++)
        {
            System.out.println(data[i]);
        }
        System.out.println("------我是分割線------");
        String data1[]=str.split(" ",3);   //按照空格拆分為3個字符數(shù)組元素
        for(int x=0;x<data1.length;x++)
        {
            System.out.println(data1[x]);
        }
    }
    }

如果用“.”或“|”作為分隔的話必須寫法如下String split("\.") 或String split("\|")。如果用“\”作為分隔必須寫成String split("\\")。如果在一個字符中有多個分隔符,可以用“|”作為連接符,比如str="account=8 and uu=45 or n=25",把三個都分隔出來可以用Str.splitz"and|or)",即用and或or進行分隔。

方法名稱 類型 描述
public String concat(String str) 普通 字符串連接,功能與“+”操作一樣
public String intern() 普通 入池
public int length 普通 取得字符串長度
public boolean isEmpty() 普通 判斷是否為空字符串(但不是NULL)
public String toLowerCase() 普通 字符串轉(zhuǎn)小寫
public String toUpperCase 普通 字符串轉(zhuǎn)大寫
public String trim 普通 去掉字符串前后空格

其他方法

方法名稱 類型 描述
public String concat(String str) 普通 字符串連接,功能與“+”操作一樣
public String intern() 普通 入池
public int length 普通 取得字符串長度
public boolean isEmpty() 普通 判斷是否為空字符串(但不是NULL)
public String toLowerCase() 普通 字符串轉(zhuǎn)小寫
public String toUpperCase 普通 字符串轉(zhuǎn)大寫
public String trim 普通 去掉字符串前后空格
//字符串常用方法
public class Main
{
    public static void main(String[] args)
    {
        String str="Hello World...";
        System.out.println("原始字符串內(nèi)容【"+str+"】"+",長度:"+str.length());  //求字符串長度
        System.out.println("原始字符串內(nèi)容【"+str+"】"+",長度:"+str.trim().length());  //去掉字符串前后空格的長度
        System.out.println("".isEmpty());  //判斷字符串是否為空
        System.out.println(str.isEmpty());  //判斷str字符串是否為空
        System.out.println("Hello World!!".toUpperCase());   //字符串字符全變大寫
        System.out.println("Hello World!!".toLowerCase());   //字符串字符全變小寫
        System.out.println(str.concat("java"));   //字符串連接
    }
}

總結

String str=new String("java");
1,創(chuàng)建String對象的個數(shù)是兩個對象,一個是“java”,一個是指向“java”的引用對象str。
2,java中堆內(nèi)容和棧內(nèi)存區(qū)別
堆內(nèi)容是一個子集。棧內(nèi)存存取速度僅次于寄存器,棧內(nèi)存里面的數(shù)據(jù)可共享,但其中數(shù)據(jù)大小和生存期必須在運行前確定。堆內(nèi)容是運行時可動態(tài)分配的數(shù)據(jù)區(qū),從速遞看比堆內(nèi)存慢,堆內(nèi)容里面數(shù)據(jù)不共享,大小和生存期都可以運行時在確定。new關鍵字是運行時在堆內(nèi)容里面創(chuàng)建對象。每new一次都一定會創(chuàng)建新對象,因為堆數(shù)據(jù)不共享。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內(nèi)部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,626評論 18 399
  • 一、String 類 1、定義: 1、從概念上講,java字符串就是Unicode字符序列。每個用雙引號括起來的字...
    玉圣閱讀 1,742評論 0 1
  • JAVA Doc public final class String extends Object impleme...
    風語安然閱讀 1,071評論 0 3
  • 在編寫程序的過程中,不了避免的要用到字符串,所以String類的常用方法的用法是必須掌握的。學習一個類的使用方法最...
    Geg_Wuz閱讀 1,482評論 0 4
  • 1、Javascript只有兩種作用域:一種是全局作用域,變量在整個程序中一直存在,所有地方都可以讀取;另一種是函...
    青春前行閱讀 312評論 0 0

友情鏈接更多精彩內(nèi)容