3.4補

來源:互聯網
上載者:User

標籤:

①常用類String②Regex③Stringbuffer④Stringbuilder

一、String
①String記憶體分析
String str0 = "hello";預先放到資料區段的常量池
String str1 = "hello";常量池裡邊已有,引用直接指向它
String str2 = new String("hello");堆中,新的
String str3 = new String("hello");堆中,新的

str3 = str2 ×,=比較的是引用,不相等,String重寫的equals方法比較的是內容,相等

str3 = str2;str2 = "world";
System.out.println("str3");結果為hello,沒有變,只是str2的引用指向了world而已,str3的引用還是指向hello

String的內容是不可變的,不管是常量池的對象,還是堆中的對象

+ 字串連結符

②String的基礎方法
-equalsIgnoreCase("str");忽略大小寫比較
-compareTo字串按字典順序比較,依次比較第一個不同字母的ASCII,方式是相減,如果都相同在用長度相減。
-length()
-charAt()取出某個位置的char值,所以是char字元,作比較的時候是ASCII,所以在作比較的時候,一定要用‘0‘,‘a‘比較,或者是ASCII
-tocharArray();-getBytes()
-indexOf("e",0);首次出現的下標,不寫預設從開始
-lastIndexOf();
-toUpperCase();全大寫,可以指定位置
-toLowerCase();全小寫
-startWith("he");判斷開頭
-endWith("he")
-contains("he");包含子字串
-concat("he");+在結尾,元字串沒變,如果要新的需要接收
-substring(1,3);截取子字串,前閉後開,
-substring(1);截取1到最後
-replace("L","you")替換,也可以是字元


③String的強力方法
-trim();去掉字串前後空格,用在接收使用者輸入 input.trim().equals();
-split();根據Regex拆分;

String birthday = "1990-1-1";
String[] results = birthday.split("-");
分隔字元前邊沒有東西,會有一個空串,最後一個分隔字元沒有東西,不會返回空串
字串 "boo:and:foo" 使用這些參數可產生以下結果:

Regex Limit 結果 
: 2 { "boo", "and:foo" } 
: 5 { "boo", "and", "foo" } 
: -2 { "boo", "and", "foo" } 
o 5 { "b", "", ":and:f", "", "" } 
o -2 { "b", "", ":and:f", "", "" } 
o 0 { "b", "", ":and:f" }

字串為空白和空串不一樣
空串:String str = ""; 引用指向""
為空白:String str = null;引用為空白

判斷字串非空:
if(str != null && str.trim().eauals(""))

二、Regex regex 字串模板
Regex本身是個字串
①[【】表示一個字元
[0-9][\d]都表示一個數字
[abc]表示a、b、c
[a-zA-z0-9]表示字母或數字

[abc]a、b 或 c(簡單類) 
[^abc] 任何字元,除了 a、b 或 c(否定) 
[a-zA-Z] a 到 z 或 A 到 Z,兩頭的字母包括在內(範圍) 
[a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](並集)

String regex = "0830[0-9]{7}"
if(input.matches(regex)){}

②{}表示前邊出現的次數
{m,n}最少m次,最多n次
{m,}最少m次,最多不限
{m}只能m次

*任意次 a[0-9]*a√
+至少一次a×a0√
?0-1次

?.要用這些本身,用轉義,\\? \\. 如果在字串中有?.雖然可以直接用,但是不準確,因為尤其特殊含義

③(|)或,分組,滿足一個即可
(abc|12|k[65]?)
regex = "0830([0-9]{4}|110|120|119)";

三、StringBuffer
①不能直接用 = 賦值調用構造new StringBuffer(String str)
②不能用+連結字元-append
③內容可變,大量的String累加,用StringBuffer
④安全執行緒,效率低,(一定)(執行,使用效率)

如果線程不安全,效率高,速度快(StringBuilder)

方法:
-append
-insert(int,"he")插入,在offset處插入
-delete(int start,end)刪除,前閉後開
-charAt
-length
-indexof(String,from index)
-setCharAt()
-repalce(start,end,str)
-reverse反轉
-toString

四、StringBuilder
相容StringBuffer API
不保證線程同步,線程不安全,效率快

所以一般不需要安全執行緒的時候,普通的字串大量操作都用StringBuilder

3.4補

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.