字符串的處理方法總結

String類和StringBuffer類

1、String處理一些小的文本

StringBuffer處理大型文本

原因:用String處理大型文本,會消耗大量系統資源。

2、String類一旦產生字符串,某對象不可變。

雖通過各種系統方法操作字符串,但不改變對象本身,而產生新的字符串。

StringBuffer類處理可變字符串。

不產生新的字符串。(兩種對字符串的操作方法不同)

3、String類

內存分配是按對象包的實際字符分配。

StringBuffer類

內存分配,除當前字符空間所佔處,還提供16個字符大小的緩衝區。

字符串處理類——String(共9種)下面是其中6中常用的

格式:字符串類型  字符串名=字符串內容

1、字符串的默認構造器

"String()"  最簡單的構造器(不帶參數)

class Str

{

public static void main(String[] args)

{

String str = new String();

System.out.println(str);

}

}

2、字節參數構造器

"String(byte[]  byte)"將字節數組中的元素作爲字符串對象

class Str

{

public static void main(String[] args)

{

byte[]  b = {97,98,99};

String str = new String(b);

System.out.println(str);

}

}

3、獲取指定字節數的構造器

"String(byte[]  byte, int offset, int length)"

構造器含義:將字節數組中從"offset"指定的位置開始到"length"結束,其中間的字符構成字符串對象。

class Str

{

public static void main(String[] args)

{

byte[] b = {97,98,99,100,101,102};

String str = new String(b,3,2);

System.out.println(str);

}

}

4、將字節型數據轉換爲字符集輸出的構造器。

"String(byte[]  byte, int offset, int length,String charsetName)"

字符集一般有"us-ascii","iso-8859-1","utf-8","utf-16be","utf-16le","utf16"等

5、字符數組的構造器

"String(char[] value)"這個構造器和第二個很像

class Str

{

public static void main(String[] args)

{

char[] c = {'w','e','l','c','o','m','e'};

String str = new String(c);

System.out.println(str);

}

}

6、截取字符串內容的構造器

"String(char[] value, int offset, int count)"

含義:江字符數組從"offset"開始,"count"結束,中間的字符連接成字符串。


class Str

{

public static void main(String[] args)

{

char[] c = {'w','e','l','c','o','m','e'};

String str = new String(c,3,4);

System.out.println(str);

}

}

字符串的處理方法:

1、串連接:兩種方法

A、使用"+"

B、使用方法函數concat(String str)

2、提取子字符串

方式1、"substring(int beginIndex, int endIndex)"指提取有beginIndex位置開始,可以endIndex爲結束位置的字符串

方式2、"substring(int Index)"值提取從Index指定位置開始,一直到字符串最後

3、從字符串中分解字符

char At(int index)

4、獲取字符串長度

length()   數組length是屬性,字符串length()是方法

5、測試字符串是否相等

方法1、equals(String str)不忽略字符串大小寫

方法2、equalsIgnose(String str)忽略字符串大小寫

6、查找特定字符串

方法1、index Of(子串內容)

方法2、starts With(子串內容)

方法3、ends With(子串內容)

7、從基本類型轉換成字符串

value Of()

8、to String()

1,String str = "小明"‘

System.out.println(str);

2,String str = "小明';

System.out.println(str.toString());

區別: 1是將對象作爲參數

2是將對象中的字符串提取出來,再輸出


發佈了15 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章