SplitConcatWithAMP
功能描述:
1、将字符串数组连接为整个字符串,'&' 为连接符
特例:如果 array 为 null 或 empty,抛出异常。因为这时无法转换!
public static String arrayToStringWithAMP( String[] array ) throws Exception
2、字符串切割为字符数组,'&'为切割符
特例:如果 str 为 null,抛出异常。这时也无法转换!
public static String[] stringToArrayWithAMP( String str ) throws Exception
3、将 "&" 转换为 "&" (因为 "&" 为特殊字符)。注意:"&" 的 "&" 不做处理
public static String encode( String str )
4、将 "&" 还原为 "&"
public static String decode( String str )
public class SplitConcatWithAMP {//Array to string concat with "&"//If array items contain "&" replace it to "&"public static String arrayToStringWithAMP( String[] array ) throws Exception{if( array == null || array.length == 0 ){throw new Exception("Array is null or empty, can not convert to string!");}StringBuilder sb = new StringBuilder();for( String s : array ){sb.append( encode(s) );sb.append( "&" );}return removeLastAMP( sb.toString() );}//Remove last "&" in stringprivate static String removeLastAMP( String str ){return str.substring( 0, str.length()-1 );}//String to array split with "&"//But if is "&" ,do not splitpublic static String[] stringToArrayWithAMP( String str ) throws Exception{if( str == null ){throw new Exception("String is null, Can not convert to array!");}String[] result = str.split( "&(?!amp;)" );for( int i=0 ; i<result.length ; i++ ){result[i] = decode( result[i] );}return result;}//Encode "&" in String to "&"//But if is "&" ,do not change.public static String encode( String str ){if( str == null){return null;}return str.replaceAll( "&(?!amp;)", "&" );}//Decode "&" in string to "&"public static String decode( String str ){if( str == null ){return null;}return str.replaceAll( "&", "&" );}}
演示:
public static void main(String[] args) throws Exception {String[] array = new String[]{"超人", "abc", "真的&可以区分", "怀&疑", "gg"};//RightSystem.out.println( "Right Demo!" );System.out.println( Arrays.toString(array) );String temp = arrayToStringWithAMP(array);System.out.println( temp );array = stringToArrayWithAMP(temp);System.out.println( Arrays.toString( array ) );//ErrorSystem.out.println("Error Demo!");errorDemo();}static void errorDemo(){String string = "超人&abc&真的&可以区分&怀&疑&gg";String[] arr = string.split( "&" );System.out.println( Arrays.toString(arr) );}
输出结果:
Right Demo!
[超人, abc, 真的&可以区分, 怀&疑, gg]
超人&abc&真的&可以区分&怀&疑&gg
[超人, abc, 真的&可以区分, 怀&疑, gg]
Error Demo!
[超人, abc, 真的, 可以区分, 怀, amp;疑, gg]
从上面的Right Demo结果可以看出:数组 -> 字符串 -> 数组
如果数组项中包含 "&",可以正确还原。
如果数组项中包含 "&",会还原为 "&"。(但其表达的意义是一致的)