判斷功能的方法
public boolean equals (Object anObject) :將此字符串與指定對象進行比較。
public boolean equalsIgnoreCase (String anotherString) :將此字符串與指定對象進行比較,忽略大小寫。
public class String_Demo01 { public static void main(String[] args) { // 創建字符串對象 String s1 = "hello"; String s2 = "hello"; String s3 = "HELLO"; // boolean equals(Object obj):比較字符串的內容是否相同 System.out.println(s1.equals(s2)); // true System.out.println(s1.equals(s3)); // false System.out.println("-----------"); //boolean equalsIgnoreCase(String str):比較字符串的內容是否相同,忽略大小寫 System.out.println(s1.equalsIgnoreCase(s2)); // true System.out.println(s1.equalsIgnoreCase(s3)); // true System.out.println("-----------"); } }
Object 是” 對象”的意思,也是一種引用類型。作為參數類型,表示任意對象都可以傳遞到方法中
注意:
2個字符串使用==比較運算符,比較的是地址值,如果使用的是equals方法,比較的是字符串內容是否相等
獲取功能的方法
public int length () :返回此字符串的長度。
String s = "helloworld"; //int length():獲取字符串的長度,其實也就是字符個數 System.out.println(s.length());//10
public String concat (String str) :將指定的字符串連接到該字符串的末尾。
String s = "helloworld"; //String concat:將指定的字符串連接到該字符串的末尾 String s2 = s.concat("**hello itheima"); System.out.println(s2);//helloworld**hello itheima
public char charAt (int index) :返回指定索引處的 char值。
String s = "helloworld"; //char charAt:獲取指定索引處的字符 System.out.println(s.charAt(0));//h System.out.println(s.charAt(1));//e
public int indexOf (String str) :返回指定子字符串第一次出現在該字符串內的索引。
String s = "helloworld"; // 獲取子字符串第一次出現在該字符串內的索引,沒有返回-1 System.out.println(s.indexOf("l"));//2 System.out.println(s.indexOf("wow"));//-1 System.out.println(s.indexOf("ak"));//-1
public String substring (int beginIndex) :返回一個子字符串,從beginIndex開始截取字符串到字符串結尾。
String s = "helloworld"; // 從beginIndex開始截取字符串到字符串結尾 System.out.println(s.substring(0));//helloworld System.out.println(s.substring(5));//world
public String substring (int beginIndex, int endIndex) :返回一個子字符串,從beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。
String s = "helloworld"; // 從beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。 System.out.println(s.substring(0, s.length()));//helloworld System.out.println(s.substring(3,8));//lowor
轉換功能的方法
public char[] toCharArray () :將此字符串轉換為新的字符數組。
String s = "HelloWorld!"; //char[] toCharArray:把字符串轉換為字符數組 char[] chs = s.toCharArray();
public byte[] getBytes () :使用平台的默認字符集將該 String編碼轉換為新的字節數組。
String s = "HelloWorld!"; byte[] bytes = s.getBytes();
public String replace (CharSequence target, CharSequence replacement) :將與target匹配的字符串使用replacement字符串替換。
String str = "itcast itheima";
String replace = str.replace("it","IT");
分割功能的方法
有些特殊符號需要用 反斜杠 \ 轉義,在Java要用兩個反斜杠 \\
//String分割 String s = "aa|bb|cc"; String[] strArray = s.split("\\|"); for(int i = 0; i < strArray.length; i++){ System.out.print(strArray[i]); }
一些常用方法
boolean contains(CharSequence s): 判斷字符串中是否包含指定字符。
String s = "djlfdjksdlka"; boolean str = s.contains("g"); System.out.println("str" + str);