java string詳解

java中String的常用方法

1、length()字符串的長度

例:char chars[]={'a','b'.'c'};

String s=new String(chars);

int len=s.length();

2、charAt()截取一個字符

例:char ch;

ch="abc".charAt(1); 返回'b'

3、 getChars()截取多個字符

void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)

sourceStart指定了子串開始字符的下標(biāo),sourceEnd指定了子串結(jié)束后的下一個字符的下標(biāo)。因此, 子串包含從sourceStart到sourceEnd-1的字符。接收字符的數(shù)組由target指定,target中開始復(fù)制子串的下標(biāo)值是targetStart。

例:String s="this is a demo of the getChars method.";

char buf[]=new char[20];

s.getChars(10,14,buf,0);

4、getBytes()

替代getChars()的一種方法是將字符存儲在字節(jié)數(shù)組中,該方法即getBytes()。

5、toCharArray()

6、equals()和equalsIgnoreCase()比較兩個字符串

7、regionMatches()用于比較一個字符串中特定區(qū)域與另一特定區(qū)域,它有一個重載的形式允許在比較中忽略大小寫。

boolean regionMatches(int startIndex,String str2,int str2StartIndex,int numChars)

boolean regionMatches(boolean ignoreCase,int startIndex,String str2,int str2StartIndex,int numChars)

8、startsWith()和endsWith()startsWith()方法決定是否以特定字符串開始,endWith()方法決定是否以特定字符串結(jié)束

9、equals()和==

equals()方法比較字符串對象中的字符,==運算符比較兩個對象是否引用同一實例。

例:String s1="Hello";

String s2=new String(s1);

s1.eauals(s2); //true

s1==s2;//false

10、compareTo()和compareToIgnoreCase()比較字符串

11、indexOf()和lastIndexOf()

indexOf() 查找字符或者子串第一次出現(xiàn)的地方。

lastIndexOf() 查找字符或者子串是后一次出現(xiàn)的地方。

12、substring()它有兩種形式,第一種是:String substring(int startIndex)

第二種是:String substring(int startIndex,int endIndex)

13、concat()連接兩個字符串

14 、replace()替換

它有兩種形式,第一種形式用一個字符在調(diào)用字符串中所有出現(xiàn)某個字符的地方進行替換,形式如下:

String replace(char original,char replacement)

例如:String s="Hello".replace('l','w');

第二種形式是用一個字符序列替換另一個字符序列,形式如下:

String replace(CharSequence original,CharSequence replacement)

15、trim()去掉起始和結(jié)尾的空格

16、valueOf()轉(zhuǎn)換為字符串

17、toLowerCase()轉(zhuǎn)換為小寫

18、toUpperCase()轉(zhuǎn)換為大寫

19、StringBuffer構(gòu)造函數(shù)

StringBuffer定義了三個構(gòu)造函數(shù):

StringBuffer()

StringBuffer(int size)

StringBuffer(String str)

StringBuffer(CharSequence chars)

(1)、length()和capacity()一個StringBuffer當(dāng)前長度可通過length()方法得到,而整個可分配空間通過capacity()方法得到。

(2)、ensureCapacity()設(shè)置緩沖區(qū)的大小

void ensureCapacity(int capacity)

(3)、setLength()設(shè)置緩沖區(qū)的長度

void setLength(int len)

(4)、charAt()和setCharAt()

char charAt(int where)

void setCharAt(int where,char ch)

(5)、getChars()

void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)

(6)、append()可把任何類型數(shù)據(jù)的字符串表示連接到調(diào)用的StringBuffer對象的末尾。

例:int a=42;

StringBuffer sb=new StringBuffer(40);

String s=sb.append("a=").append(a).append("!").toString();

(7)、insert() 插入字符串

StringBuffer insert(int index,String str)

StringBuffer insert(int index,char ch)

StringBuffer insert(int index,Object obj)

index指定將字符串插入到StringBuffer對象中的位置的下標(biāo)。

(8)、reverse() 顛倒StringBuffer對象中的字符

StringBuffer reverse()

(9)、delete()和deleteCharAt() 刪除字符

StringBuffer delete(int startIndex,int endIndex)

StringBuffer deleteCharAt(int loc)

(10)、replace() 替換

StringBuffer replace(int startIndex,int endIndex,String str)

(11)、substring() 截取子串

String substring(int startIndex)

String substring(int startIndex,int endIndex)

例子:

//String所給出的方法均可以直接調(diào)用

public class Test{

public static void main(String[] args){

String s = "Welcome to Java World!";

String s1 = " sun java ";

System.out.println(s.startsWith("Welcome"));//字符串以Welcome開頭

System.out.println(s.endsWith("World"));//字符串以World結(jié)尾

String sL = s.toLowerCase();//全部轉(zhuǎn)換成小寫

String sU = s.toUpperCase();//全部轉(zhuǎn)換成大寫

System.out.println(sL);

System.out.println(sU);

String b = s.substring(11);//從第十一位開始

System.out.println(b);

String c = s.substring(8,11);//從第八位開始在第十一位結(jié)束

System.out.println(c);

String d = s1.trim();//去掉首尾的空格

System.out.println(d);

String s2 = "我是程序員,我在學(xué)java";

String e = s2.replace("我","你");

System.out.println(e);

int f = 5;

String s3 = String.valueOf(f);

System.out.println(s3);

String s4 = "我是,這的,大王";

String[] g = s4.split(",");

System.out.println(g[0]);

當(dāng)把字符串轉(zhuǎn)換成基本類型時,例如,int,integer.praseInt(String s)

當(dāng)把基本類型轉(zhuǎn)換成字符串時,例如,static String valueOf(int i)


一、構(gòu)造函數(shù)

String(byte[ ]bytes):通過byte數(shù)組構(gòu)造字符串對象

String(char[ ]value):通過char數(shù)組構(gòu)造字符串對象

String(Stingoriginal):構(gòu)造一個original副本。即:拷貝一個original

String(StringBufferbuffer):通過StringBuffer數(shù)組構(gòu)造字符串對象。

例如:

byte[] b = {'a','b','c','d','e','f','g','h','i','j'};

char[] c = {'0','1','2','3','4','5','6','7','8','9'};

String sb = new String(b);???????????????? //abcdefghij

String sb_sub = new String(b,3,2);???? //de

String sc = new String(c);????????????????? //0123456789

String sc_sub = new String(c,3,2);??? //34

String sb_copy = new String(sb);?????? //abcdefghij

System.out.println("sb:"+sb);

System.out.println("sb_sub:"+sb_sub);

System.out.println("sc:"+sc);

System.out.println("sc_sub:"+sc_sub);

System.out.println("sb_copy:"+sb_copy);

輸出結(jié)果sb:abcdefghij

sb_sub:de

sc:0123456789

sc_sub:34

sb_copy:abcdefghij

二、方法:

說明:①、所有方法均為public。

②、書寫格式: [修飾符] <返回類型><方法名([參數(shù)列表])>

例如:static int parseInt(String s)

表示此方法(parseInt)為類方法(static),返回類型為(int),方法所需要為String類型。

1.charcharAt(int index)取字符串中的某一個字符,其中的參數(shù)index指的是字符串中序數(shù)。字符串的序數(shù)從0開始到length()-1 。

例如:String s = new String("abcdefghijklmnopqrstuvwxyz");

System.out.println("s.charAt(5): " + s.charAt(5) );

結(jié)果為: s.charAt(5): f

2.int compareTo(String anotherString)當(dāng)前String對象與anotherString比較相等關(guān)系返回0不相等時,從兩個字符串第0個字符開始比較,返回第一個不相等的字符差,另一種情況,較長字符串的前面部分恰巧是較短的字符串,返回它們的長度差。

3.int compareTo(Object o):如果o是String對象,和2的功能一樣;否則拋出ClassCastException異常。

例如:String s1 = new String("abcdefghijklmn");

String s2 = new String("abcdefghij");

String s3 = new String("abcdefghijalmn");

System.out.println("s1.compareTo(s2): " + s1.compareTo(s2) ); //返回長度差

System.out.println("s1.compareTo(s3): " + s1.compareTo(s3) ); //返回'k'-'a'的差

結(jié)果為:s1.compareTo(s2): 4

s1.compareTo(s3): 10

4.String concat(String str)將該String對象與str連接在一起。

5.boolean contentEquals(StringBuffer sb):將該String對象與StringBuffer對象sb進行比較。

6.static String copyValueOf(char[] data)

7.static String copyValueOf(char[] data, int offset, int count):這兩個方法將char數(shù)組轉(zhuǎn)換成String,與其中一個構(gòu)造函數(shù)類似。

8.boolean endsWith(String suffix)該String對象是否以suffix結(jié)尾

例如:String s1 = new String("abcdefghij");

String s2 = new String("ghij");

System.out.println("s1.endsWith(s2): " + s1.endsWith(s2) );

結(jié)果為:s1.endsWith(s2): true

9.boolean equals(Object anObject)當(dāng)anObject不為空并且與當(dāng)前String對象一樣,返回true;否則,返回false

10.byte[] getBytes()將該String對象轉(zhuǎn)換成byte數(shù)組

11.void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)該方法將字符串拷貝到字符數(shù)組中。其中,srcBegin為拷貝的起始位置、srcEnd為拷貝的結(jié)束位置、字符串?dāng)?shù)值dst為目標(biāo)字符數(shù)組、dstBegin為目標(biāo)字符數(shù)組的拷貝起始位置。

例如:char[] s1 = {'I',' ','l','o','v','e',' ','h','e','r','!'};//s1=I love her!

String s2 = new String("you!"); s2.getChars(0,3,s1,7); //s1=I love you!

System.out.println( s1 );

結(jié)果為:I love you!

12.int hashCode()返回當(dāng)前字符的哈希表碼

13.int indexOf(int ch)只找第一個匹配字符位置

14.int indexOf(int ch, intfromIndex)從fromIndex開始找第一個匹配字符位置

15.int indexOf(String str)只找第一個匹配字符串位置

16.int indexOf(String str, int fromIndex)從fromIndex開始找第一個匹配字符串位置

例如:String s = new String("write once, run anywhere!");

String ss = new String("run");

System.out.println("s.indexOf('r'): " + s.indexOf('r') );

System.out.println("s.indexOf('r',2): " + s.indexOf('r',2) );

System.out.println("s.indexOf(ss): " + s.indexOf(ss) );

結(jié)果為:s.indexOf('r'): 1

s.indexOf('r',2): 12

s.indexOf(ss): 12

17.int lastIndexOf(int ch)18.int lastIndexOf(int ch, int fromIndex)19.int lastIndexOf(String str)20.int lastIndexOf(String str, int fromIndex)以上四個方法與13、14、15、16類似,不同的是:找最后一個匹配的內(nèi)容

public class CompareToDemo {

public static void main (String[] args) {

String s1 = new String("acbdebfg");

System.out.println(s1.lastIndexOf((int)'b',7));

}

}

運行結(jié)果5

(其中fromIndex的參數(shù)為7,是從字符串acbdebfg的最后一個字符g開始往前數(shù)的位數(shù)。既是從字符c開始匹配,尋找最后一個匹配b的位置。所以結(jié)果為5

21.int length()返回當(dāng)前字符串長度

22.String replace(charoldChar, charnewChar)將字符號串中第一個oldChar替換成newChar

23.boolean startsWith(String prefix)該String對象是否以prefix開始

24.boolean startsWith(Stringprefix, inttoffset)該String對象從toffset位置算起,是否以prefix開始

例如:String s = new String("write once, run anywhere!");

String ss = new String("write");

String sss = new String("once");

System.out.println("s.startsWith(ss): " + s.startsWith(ss) );

System.out.println("s.startsWith(sss,6): " + s.startsWith(sss,6) );

結(jié)果為:s.startsWith(ss): true

s.startsWith(sss,6): true

25.String substring(int beginIndex)取從beginIndex位置開始到結(jié)束的子字符串

26.String substring(int beginIndex, int endIndex)取從beginIndex位置開始到endIndex位置的子字符串

27.char[ ] toCharArray()將該String對象轉(zhuǎn)換成char數(shù)組

28.String toLowerCase()將字符串轉(zhuǎn)換成小寫

29.String toUpperCase():將字符串轉(zhuǎn)換成大寫。

例如:String s = new String("java.lang.Class String");

System.out.println("s.toUpperCase(): " + s.toUpperCase() );

System.out.println("s.toLowerCase(): " + s.toLowerCase() );

結(jié)果為:s.toUpperCase(): JAVA.LANG.CLASS STRING

s.toLowerCase(): java.lang.class string

30.static String valueOf(boolean b)31.static String valueOf(char c)32.static String valueOf(char[] data)33.static String valueOf(char[] data, int offset, int count)34.static String valueOf(double d)35.static String valueOf(float f)

36.static String valueOf(int i)37.static String valueOf(long l)38.static String valueOf(Object obj)以上方法用于將各種不同類型轉(zhuǎn)換成Java字符型。這些都是類方法。

Java中String類的常用方法:

public char charAt(int index)

返回字符串中第index個字符;

public int length()返回字符串的長度;

public int indexOf(String str)返回字符串中第一次出現(xiàn)str的位置;

public int indexOf(String str,int fromIndex)返回字符串從fromIndex開始第一次出現(xiàn)str的位置;

public boolean equalsIgnoreCase(String another)

比較字符串與another是否一樣(忽略大小寫);

public String replace(char oldchar,char newChar)

在字符串中用newChar字符替換oldChar字符

public boolean startsWith(String prefix)

判斷字符串是否以prefix字符串開頭;

public boolean endsWith(String suffix)判斷一個字符串是否以suffix字符串結(jié)尾;

public String toUpperCase()

返回一個字符串為該字符串的大寫形式;

public String toLowerCase()返回一個字符串為該字符串的小寫形式

public String substring(int beginIndex)返回該字符串從beginIndex開始到結(jié)尾的子字符串;

public String substring(int beginIndex,int endIndex)

返回該字符串從beginIndex開始到endsIndex結(jié)尾的子字符串

public String trim()返回該字符串去掉開頭和結(jié)尾空格后的字符串

public String[] split(String regex)

將一個字符串按照指定的分隔符分隔,返回分隔后的字符串?dāng)?shù)組

實例:

public classSplitDemo{

public static void main (String[] args) {

Stringdate= "2008/09/10";

String[ ]dateAfterSplit= new String[3];

dateAfterSplit=date.split("/");//以“/”作為分隔符來分割date字符串,并把結(jié)果放入3個字符串中。

for(int i=0;i<dateAfterSplit.length;i++)

System.out.print(dateAfterSplit[i]+" ");

}

}

運行結(jié)果2008 09 10????????? //結(jié)果為分割后的3個字符串

實例:

TestString1.java:

程序代碼

public class TestString1

{

public static void main(String args[]) {

String s1 = "Hello World" ;

String s2 = "hello world" ;

System.out.println(s1.charAt(1)) ;

System.out.println(s2.length()) ;

System.out.println(s1.indexOf("World")) ;

System.out.println(s2.indexOf("World")) ;

System.out.println(s1.equals(s2)) ;

System.out.println(s1.equalsIgnoreCase(s2)) ;

String s = "我是J2EE程序員" ;

String sr = s.replace('我','你') ;

System.out.println(sr) ;

}

}

TestString2.java:

程序代碼

public class TestString2

{

public static void main(String args[]) {

String s = "Welcome to Java World!" ;

String s2 = "?? magci?? " ;

System.out.println(s.startsWith("Welcome")) ;

System.out.println(s.endsWith("World")) ;

String sL = s.toLowerCase() ;

String sU = s.toUpperCase() ;

System.out.println(sL) ;

System.out.println(sU) ;

String subS = s.substring(11) ;

System.out.println(subS) ;

String s1NoSp = s2.trim() ;

System.out.println(s1NoSp) ;

}

JAVA的String 類【轉(zhuǎn)】 - 火之光 - 博客園

www.runoob.com/java/java-string.html

Java中String類的方法及說明 - 吳勇壽 - 博客園

深入理解Java:String - 牛奶、不加糖 - 博客園

www.runoob.com/java/java-stringbuffer.html(Java StringBuffer和StringBuilder類)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,024評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,328評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,878評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,098評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,616評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,554評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,725評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 43,971評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,339評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,695評論 2 370

推薦閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,705評論 18 399
  • 【程序1】 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔...
    葉總韓閱讀 5,146評論 0 41
  • [TOC] StringBuffer類 StringBuffer類概述及其構(gòu)造方法 StringBuffer類概述...
    lutianfei閱讀 476評論 0 1
  • Java經(jīng)典問題算法大全 /*【程序1】 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子...
    趙宇_阿特奇閱讀 1,885評論 0 2
  • 一、 1、請用Java寫一個冒泡排序方法 【參考答案】 public static void Bubble(int...
    獨云閱讀 1,402評論 0 6