一、實例化String對象java
直接賦值(節省內存)
數組
使用關鍵字new
安全
"=="比較的是地址,equals比較的是內容(開發中用的較多)app
二、不可更改ui
String經常使用方法spa
一、字符串長度,length()方法 //ctrl+shift+f 快速整理代碼線程
二、字符串轉換數組:toCharArray()設計
三、從字符串中取出指定位置的字符:charAt()code
四、字符串與byte數組的轉換:getBytes()對象
五、過濾字符串中存在的字符:indexOf()
六、去掉字符串的先後空格:trim()
七、從字符串中取出子字符串:subString()
八、大小寫轉換:toLowerCase() toUpperCase()
九、判讀字符串的開頭結尾字符:endsWith() startWith()
十、替換String字符串中的一個字符:replace()
package Str; public class StringDemo01 { public static void main(String[] args) { // TODO Auto-generated method stub String str = "hello"; char s[]=str.toCharArray(); for(int i=0;i<str.length();i++){ System.out.print(s[i]+" "); } String str1="helloword"; System.out.println(str1.charAt(5)); byte b[]=str1.getBytes(); for(int j=0;j<b.length;j++){ System.out.println(new String(b)+"\t"); } System.out.println(str1.indexOf("d")); String str2=" ddd "; System.out.println(str2.trim()); } }
SringBuffer
一、認識SringBuffer:
緩衝區,自己也是操做字符串,可是與string不一樣,StringBuffer是能夠更改的。
StringBuffer是一個操做類,因此必須經過實例化進行操做
public class StirnBuDemo01 { public static void main(String[] args) { // TODO Auto-generated method stub StringBuffer sb=new StringBuffer(); sb.append("I am a girl"); System.out.println(sb.toString()); StringBuffer sb1=new StringBuffer(); sb1.append("hello,"); tell(sb1); System.out.println(sb1.toString()); } public static void tell(StringBuffer st){ st.append("I am three"); } }
二、StringBuffer經常使用方法:
append()
insert()
replace()
indexOf()
public class StrBuf { public static void main(String[] args) { // TODO Auto-generated method stub StringBuffer stb=new StringBuffer(); stb.append("I love"); stb.insert(1, "you"); System.out.println(stb.toString()); stb.replace(3, 5, "hell"); System.out.println(stb.toString()); System.out.println(stb.indexOf("m")); } }
StringBuffer類的應用
public class Whe { public static void main(String[] args) { // TODO Auto-generated method stub String str="hello"; for(int i=0;i<100;i++){ str=str+i; } System.out.println(str); StringBuffer str1=new StringBuffer(); str1.append("hella"); for(int i=0;i<100;i++){ str1.append(i); } System.out.println(str1.toString()); } }
StringBuilder
一、一個可變的字符序列,該類被設計做用StringBuffer的一個簡易替換,用在字符串緩衝區被單個線程使用的時候。建議優先考慮該類,速度比StringBuffer更快。
二、可是若是涉及到線程安全方面的問題,建議使用StringBuffer.
三、經常使用方法:
append()
insert()