當前位置:才華齋>計算機>java語言>

java常用字串介紹

java語言 閱讀(2.38W)

Java字串類(ng)是Java中使用最多的類,也是最為特殊的一個類,很多時候,我們對它既熟悉又陌生。下面是小編為大家搜尋整理的Java常用字串,希望大家能有所收穫,更多精彩內容請及時關注我們考試網!

java常用字串介紹

一、建立並初始化字串:

1、使用字串常量直接初始化 String s=“hello!”;

2、使用構造方法建立並初始化 String();//初始化一個物件,表示空字元序列

String(value);//利用已存在的字串常量建立一個新的物件

String (char[] value);//利用一個字元陣列建立一個字串

String(char[] value,int offset,int count);//擷取字元陣列offset到count的字元建立一個非空串

String(StringBuffer buffer);//利用StringBuffer物件初始化String物件

二、String類主要方法的使用:

1、獲取長度 *th();//這與陣列中的獲取長度不同,*th;

2、比較字串(1) equals() //判斷內容是否相同

(2)compareTo() //判斷字串的大小關係

(3)compareToIgnoreCase(String int) //在比較時忽略字母大小寫

(4)== //判斷內容與地址是否相同

(5)equalsIgnoreCase() //忽略大小寫的情況下判斷內容是否相同

如果想對字串中的部分內容是否相同進行比較,可以用

(6)reagionMatches() //有兩種 public boolean regionMatches(int toffset, String other,int ooffset,int len);表示如果String物件的一個子字串與引數other的一個子字串是相同的字元序列,則為true.要比較的String 物件的字串從索引toffset開始,other的字串從索引ooffset開始,長度為len。

public boolean reagionMatches(boolean ignoreCase,int toffset,String other,int ooffset,int len);//用布林型別的引數指明兩個字串的比較是否對大小寫敏感。

三、查詢字串中某個位置的字元

public char charAt(int index);//返回指定索引index位置上的字元,索引範圍從0開始

四、查詢指定字串在字串中第一次或最後一詞出現的位置

在String類中提供了兩種查詢指定位置的`字串第一次出現的位置的方法

(1)public int indexOf(String str);//從字串開始檢索str,並返回第一次出現的位置,未出現返回-1

(2)public int indexOf(String str,int fromIndex);//從字串的第fromIndex個字元開始檢索str

查詢最後一次出現的位置有兩種方法

(1)public int lastIndexOf(String str);

(2)public int lastIndexOf(String str,int fromIndex);

如果不關心字串的確切位置則可使用public boolean contains(CharSequence s);

五、檢查字串的起始字元和結束字元

開始的字串兩種方法

(1)public boolean starWith(String prefix,int toffset);//如果引數prefix表示的字串序列是該物件從索引toffset處開始的子字串,則返回true

(2)public boolean starWith(String prefix);

結束的字串方法

public boolean endsWith(String suffix);

六、擷取子串

(1)public String subString(int beginIndex);

(2)public String subString(int beginIndex,int endIndex);//返回的字串是從beginIndex開始到endIndex-1的串

要返回後4位可以這樣寫tln(*tring()(*th()-4));

七、字串的替換

兩種方法

(1)public String replace(char oldChar,char newChar);

(2)public String replace(CharSequence target,CharSequence replacement);/