1. 程式人生 > >字符串數組和字符串的轉換

字符串數組和字符串的轉換

結果 限制 需要 必須 () split obj cnblogs “.”

1.StringUtils.join(Object array[],String separator)

將數組以符號或其他字符串為間隔組成新的字符串

Object array[] 需要轉換的數組。separator組成新串的間隔符號,如 "," "|"

private static final String[] str = {"1","2","3","4"};
2 String str2 = StringUtils.join(str, "|");
3 
4 System.out.println(str2);

輸出結果:1|2|3|4

轉載自:https://www.cnblogs.com/astrocc/archive/2012/10/20/2732733.html

2.java中的spit()方法

基本格式:stringObj.split([separator,[limit]]) 參數 ,其中各個部分,stringObj這個表示的是要分割的字符串,separator表示的是字符串或 正則表達式對象,它標識了分隔字符串時使用的是一個還是多個字符。如果忽略該選項,返回包含整個字符串的單一元素數組; limit :表示的是該值用來限制返回數組中的元素個數。

此方法返回的是字符串數組,如果遇到了特殊字符,像是正則表達式,例如: | , + , * , ^ , $ , / , | , [ , ] , ( , ) , - , . , \等,需要 \ 去轉義

例如:想用 | 豎線去分割某字符,因 | 本身是正則表達式中的一部分,所以需要 \ 去轉義,因轉義使用 \, 而這個 \ 正好也是正則表達式的字符,所以還得用一個 \ , 所以需要兩個 \\。 如果用“.”作為分隔的話,必須是如下寫法:String.split("\\."),

如果用“|”作為分隔的話,必須是如下寫法:String.split("\\|"), 如果在一個字符串中有多個分隔符,可以用“|”作為連字符,比如:“a=1 and b =2 or c=3”,把三個都分隔出來,可以用String.split("and|or");

2.字符串數組轉換成字符串

例子:

String[] str = {"abc", "bcd", "def"};
StringBuffer sb = new StringBuffer();
for(int i = 0; i < str.length; i++){
 sb. append(str[i]);
}
String s = sb.toString();

如果是 “字符數組” 轉 “字符串”

char[]   data={‘a‘,‘b‘,‘c‘};   
String  s=new   String(data);

轉自:https://www.cnblogs.com/SharkBin/p/4512561.html

字符串數組和字符串的轉換