java常用字符串介紹
Java字符串類(java.lang.String)是Java中使用最多的類,也是最為特殊的一個類,很多時候,我們對它既熟悉又陌生。下面是小編為大家搜索整理的Java常用字符串,希望大家能有所收獲,更多精彩內(nèi)容請及時關(guān)注我們考試網(wǎng)!
一、創(chuàng)建并初始化字符串:
1、使用字符串常量直接初始化 String s=“hello!”;
2、使用構(gòu)造方法創(chuàng)建并初始化 String();/pic/p>
String(value);/pic/p>
String (char[] value);/pic/p>
String(char[] value,int offset,int count);/pic/p>
String(StringBuffer buffer);/pic/p>
二、String類主要方法的使用:
1、獲取長度 *.length();/pic/p>
2、比較字符串(1) equals() /pic/p>
(2)compareTo() /pic/p>
(3)compareToIgnoreCase(String int) /pic/p>
(4)== /pic/p>
(5)equalsIgnoreCase() /pic/p>
如果想對字符串中的部分內(nèi)容是否相同進行比較,可以用
(6)reagionMatches() /pic/p>
public boolean reagionMatches(boolean ignoreCase,int toffset,String other,int ooffset,int len);/pic/p>
三、查找字符串中某個位置的字符
public char charAt(int index);/pic/p>
四、查找指定字符串在字符串中第一次或最后一詞出現(xiàn)的位置
在String類中提供了兩種查找指定位置的字符串第一次出現(xiàn)的位置的方法
(1)public int indexOf(String str);/pic/p>
(2)public int indexOf(String str,int fromIndex);/pic/p>
查找最后一次出現(xiàn)的位置有兩種方法
(1)public int lastIndexOf(String str);
(2)public int lastIndexOf(String str,int fromIndex);
如果不關(guān)心字符串的確切位置則可使用public boolean contains(CharSequence s);
五、檢查字符串的起始字符和結(jié)束字符
開始的字符串兩種方法
(1)public boolean starWith(String prefix,int toffset);/pic/p>
(2)public boolean starWith(String prefix);
結(jié)束的字符串方法
public boolean endsWith(String suffix);
六、截取子串
(1)public String subString(int beginIndex);
(2)public String subString(int beginIndex,int endIndex);/pic/p>
要返回后4位可以這樣寫Syetem.out.println(*.subString()(*.length()-4));
七、字符串的替換
兩種方法
(1)public String replace(char oldChar,char newChar);
(2)public String replace(CharSequence target,CharSequence replacement);/
【java常用字符串介紹】相關(guān)文章:
java常用字符串12-15
java常用字符串方法12-17
Java字符串(String)12-26
關(guān)于Java字符串問題11-09
Java中日期與字符串的處理11-13