動手動腦之字符串
1.動手動腦之String.equals()方法
String.equals()的判等條件:用來檢測兩個String類型的對象是否相等,不能簡單用“==”來判斷兩個字符串相等。
public class fangfa { public static void main(String[] args) { String s1=new String("Hello"); String s2=new String("Hello"); System.out.println(s1==s2); System.out.println(s1.equals(s2)); String s3="Hello"; String s4="Hello"; System.out.println(s3==s4); System.out.println(s3.equals(s4)); } }
例如此段代碼,第一個輸出的為false,其余都為true。因為String1和String2為兩個對象,所以輸出false。“==”指的是兩個對象的引用相同,而“equals()”指的是兩個對象的值相等。
2.整理String類方法
(1)Length():可以求出一個字符串的長度
例:public int length()//求字符串長度
String s=”asdfgh”;
System.out.println(s.length());
(2)char():獲取制定位置的字符
例:public charAt(int index)//index 是字符下標,返回字符串中指定位置的字符
String s=”Hello”;
System.out.println(s.charAt(3));
(3)getChars():將字符從此字符串復制到目標字符數組
例:public int getChars()//將字符從此字符串復制到目標字符數組
String str = "abcdefghikl";
Char[] ch = new char[8];
str.getChars(2,5,ch,0);
(4)replace():用於在字符串中用一些字符替換另一些字符
例:public int replace()//替換字符串
String s=”\\\”;
System.out.println(s.replace(“\\\”,”///”));
(5)toUpperCase():把字符串轉化為大寫
例:public String toUpperCase()//將字符串全部轉換成大寫
System.out.println(new String(“hello”).toUpperCase());
(6)toLowerCase():把字符串轉化成小寫
例:public String toLowerCase()//將字符串全部轉換成小寫
System.out.println(new String(“HELLO”).toLowerCase());
(7)trim():去掉頭尾指針
例:public String trim()
String x=”ax c”;
System.out.println(x.trim());//是去兩邊空格的方法
(8)toCharArray():將一個字符串內容轉換為字符數組
例:String x=new String(“abcd”);// 將字符串對象中的字符轉換為一個字符數組
char myChar[]=x.toCharArray();
System.out.println(“myChar[1]”+myChar[1])
動手動腦之字符串