字符串類
字符串類屬於系統類
需要注意:字符串 是字符串常量 存在於方法區的常量池中
如何學習:系統類的方法
1.有沒有關鍵字 static 修飾
2.返回值的類型
3.方法名,一般方法名都是見名知意的
4.參數列表(看方法需要什麼)
String s1="abc"; 這種創建形式 會先去靜態區中找有沒有這樣的一個字符串
如果有地址就會指向這個字符串 ,沒有就會創建一個
String s3=new String("abc"); 會在堆中生成一個對象 在指向棧中的變量名的同時,
也指向靜態區的字符串
//修改了 字符串引用(地址)
//指向了不同的地址 而不是字符串本身被修改了
//看系統方法時 拼接 截取等操作字符串的一類方法
//都是返回一個新的字符串
String s1="abc";
s1="wanglong";
System.out.println(s1);
//s2相當於在方法區的常量池中創建了一個字符串
String s2="abc";
//s3是在堆內存中 開闢一塊空間
String s3=new String("abc");
String s4="abc";
//==對象比的是地址
System.out.println(s2==s4);
//equals 把兩個字符創轉換成字符數組 一位一位的進行比較
System.out.println(s2.equals(s4));
System.out.println(s2==s3);
//s2和s3 有什麼區別?
//s2 是一個對象 s3 是兩個對象 "abc" 和 new出來的對象
這裏列舉了一些常用的字符串方法/* 常用的方法 下面列舉了一部分
* 替換 切割 獲取子串 轉換大小寫 去空格 比較
判斷兩個字符串相等(忽略大小寫)
把字符數組 轉化爲 字符串
把字符串轉化爲 字符數組
判斷字符串是否爲空
*/
public class Demo03 {
public static void main(String[] args) {
// fun1();
// fun2();
// fun3();
// fun4();
// fun5();
// fun6();
// fun7();
}
private static void fun7() {
// 基本數據類型轉換成字符串
String valueOf = String.valueOf(1000);
System.out.println(valueOf);
}
private static void fun6() {
// 判斷字符串是否爲空
String string = "";
boolean empty = string.isEmpty();
System.out.println(empty);
// 字符串拼接
String s1 = "wan";
String s2 = "long";
String s3 = s1 + s2;
System.out.println(s3);
String concat = s1.concat(s2);
System.out.println(concat);
}
private static void fun5() {
// 把字符數組轉化成字符串
char[] array = { 'w', 'a', 'n', 'l', 'o', 'n', 'g' };
String string = new String(array);
System.out.println(string);
// 字符串轉化成字符數組
String s1 = "wanglong";
char[] charArray = s1.toCharArray();
for (char c : charArray) {
System.out.println(c);
}
}
private static void fun4() {
// 去空格
String string = " abc def ";
String trim = string.trim();
System.out.println(trim);
// 字符串比較
String s2 = "abcAB";
String s3 = "Abc";
// 相等返回的是0 返回正值說明前面大 負值前面小
// 字符不一樣的時候 按ASCII表 返回兩個字符的差值
// 長度不一樣的時候 返回的是位數的 差值
// 一位一位比較 字符不一樣就做差值
int compareTo = s2.compareTo(s3);
System.out.println(compareTo);
}
private static void fun3() {
// 獲取子字符串
String string = "wanglong";
// 從傳入的索引這一位開始截取(包括3)
String substring = string.substring(3);
System.out.println(substring);
// [0,3)留頭不留尾 實際[0,2]
String substring2 = string.substring(0, 3);
System.out.println(substring2);
}
private static void fun2() {
// 分割
String string = "wanglong.pengqian.liushankun";
// 使用轉義符
String[] split = string.split("\\.");
// 增加for循環(專門用來遍歷的)
for (String sds : split) {
// String sds 表示容器中的每一個元素
System.out.println(sds);
}
}
private static void fun1() {
String string = "wanglong";
// 替換
String replace = string.replace("w", "l");
System.out.println(replace);
// 替換字符串
String replace2 = string.replace("long", "ba");
System.out.println(replace2);
}
}