java數組和字串相互轉換

來源:互聯網
上載者:User

標籤:bbb   org   知識庫   bytes   commons   ace   sdn   .net   toc   

將字串變成數組

Java.lang包中有String.split()方法,java中通常用split()分割字串,返回的是一個數組。

特殊,逸出字元,必須加"\\"(“.”和“|”都是逸出字元)

樣本:

1、如果用“.”作為分隔的話,必須是如下寫法,String.split("\\."),這樣才能正確的分隔開,不能用String.split(".");

2、如果用“|”作為分隔的話,必須是如下寫法,String.split("\\|"),這樣才能正確的分隔開,不能用String.split("|");

3、如果在一個字串中有多個分隔字元,可以用“|”作為連字號,如,“acount=? and uu =? or n=?”,把三個都分隔出來,可以用string.split("and|or");

4、如果想在串中使用"\"字元,則也需要轉義.首先要表達"aaaa\bbbb"這個串就應該用"aaaa\\bbbb",如果要分隔就應該這樣才能得到正確結果,

String[] aa = "aaa\\bbb\\bccc".split("\\\\");

5、如果是"abc"這種字串,就直接

String string = "abc" ;

char [] stringArr = string.toCharArray(); //注意傳回值是char數組

6、如果要返回byte數組就直接使用getBytes方法就ok了:<span style="white-space:pre"></span>String string = "abc" ;<span style="white-space:pre"></span>byte [] stringArr = string.getBytes();

 

將數組變成字串
使用StringUtils中的join函數。org.apache.commons.lang.StringUtils;樣本:StringUtils.join(null)           = nullStringUtils.join([])               = ""StringUtils.join([null])          = ""StringUtils.join(["a", "b", "c"]) = "abc"StringUtils.join([null, "", "a"]) = "a"String[] str = { "1", "2", "a", "b" };// 將數組變成字串StringUtils.join(str)// 將數組用逗號分隔變成字串StringUtils.join(str, ",")

java數組和字串相互轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.