Java中的String類,JavaString類
/*
String類用於描述字串事物的
那麼它就提供了多個方法對字串進行操作
方法都會用,字串這塊就結束了
常見的操作有哪些?
“abcd”
它應該具備什麼功能,我們才能更好得操作它?
1.擷取(必須要掌握)
1.1 字串中包含的字元數,也就是字串的長度
int length() 然而數組也有長度,數組調用的length沒有括弧,是屬於屬性,但是字串是方法
1.2 根據位置擷取位置上的某個字元
char charAt(int index)
1.3 根據字元擷取該字元在字串中的位置
int indexof(int ch) 返回字元ch在字串中第一次出現的位置
int indexpf(int ch,int fromIndex) 從fromIndex指定位置開始,擷取ch在字串中出現的位置
int indexof(String str) 返回的是str在字串中第一次出現的位置
nt indexpf(String str,int fromIndex) 從fromIndex指定的位置開始,擷取str在字串中出現的位置
反向索引----方法加多一個last就可以
2.判斷
2.1 字串中是否包含某一個子串
boolean contains(str);
int indexof(int ch) 返回字元ch在字串中第一次出現的位置 有異曲同工之妙
2.2 字串中是否有內容
boolean isEmpty(); 原理就是判斷長度是否為0
2.3 字串是否是以指定內容開頭
boolean startWith(str)
2.4 字串是否是以指定內容結尾 判斷開頭,判斷結尾是bool類型的
boolean endWith(str)
2.5 判斷字串的內容是否相同 複寫了父類中的object方法
boolean equals(str);
2.6判斷內容是否相同,並忽略大小寫
boolean equalsIgnoreCsae();
3.轉換
3.1 將字元數組轉成字串
建構函式 String(chae[])
String(char[],int count) 將字元數組的一部分轉成字串
靜態方法 static String copyValue(char[]);
static String copyValue(char[],int count);
static String valueof(char[]);
3.2 將字串轉成字元數組
char[] toCharArray();
3.3 將位元組數組轉成字串
String(byte[])
String(byte[],int count)
反 byte[] getBytes();
3.4 將字串轉成位元組數組
3.5 將基礎資料型別 (Elementary Data Type)轉成字串
static String valueof(int);
static String valueof(double);
特殊:
字串和位元組數組在轉換的過程中,是可以指定編碼錶的
4.替換
String replace(oldchar,newchar); 更換的可以是字串
5.切割
String[] split(regex); 把該字元切割了,然後將每一部分組裝成數組
6.子串,擷取字串中的一部分
String substring(begin); begin是數字 從指定位置到結尾 0 1 2 如果角標不存在,會發生角標越界異常
String substring(begin,end); 包含頭,不包含尾
7.轉換 去除空格 比較
7.1 將字串轉成大寫或者小寫
String toUppercase(); 這也是為什麼java能忽略大小寫原因
String toLowercase();
7.2 將字串兩端多餘的空格去除
String trim();
7.3 對兩個字串進行自然順序的比較
int compareTo(); 開始比較,從0位置開始,以此比較,找到不同的,就相減,返回這一個值
*/
class StringMethodDemo
{
public static void method_get()
{
String str="abcdefakbf";
/*長度*/
//System.out.println(str.length()); /*如果又有字串呢?是不是要列印n多遍?怎麼辦?P1*/
sop(str.length());
/*根據索引擷取字元*/
sop(str.charAt(40)); /*當訪問到字串中不存在的角標時會發生字串角標越界異常*/
sop(str.charAt(4));
/*根據字元擷取索引*/
sop(str.indexof('a'));
sop(str.indexof('a',3));
sop(str.indexof('v',3)); /*如果沒有找到,返回的值是-1,不會出現異常*/
/*反向索引----方法*/
sop(str.lastIndexof("a")); /*輸出的角標不會變,一直從左邊開始*/
}
public static void sop(Object obj) /*無論傳什麼值進來都能列印*/
{
System.out.println(obj);
}
public static void main(String args[])
{
/*
String s1="abc";
String s2=new String("abc");
String s3="abc";
System.out.println(s1==s2); false
System.out.println(s1==s3); true?為什嗎?常量池中abc以及存在,s3發現abc存在後,就不會再開闢記憶體空間了
*/
/*P1*/
method_get();
}
}