Java Array to String arrayToString(String[] array)

Here you can find the source of arrayToString(String[] array)

Description

This takes a String[] and returns a String that can be converted back into an identical String[] using the stringToArray method.

License

Open Source License

Parameter

Parameter Description
array the String[] to convert into a String.

Return

the converted array as a String.

Declaration

public static String arrayToString(String[] array) 

Method Source Code

//package com.java2s;
//  License as published by the Free Software Foundation; either    //

public class Main {
    /**/* ww  w. j  a v a2  s.  c  om*/
     * <p>
     * This takes a String[] and returns a String that can be converted
     * back into an identical String[] using the stringToArray method.
     * </p>
     * <p>
     * The intended purpose of this is to possibly aid in implementing the
     * getStringForm() method of the abstract NodeAddressID class.
     * </p>
     * @param   array   the String[] to convert into a String.
     * @return   the converted array as a String.
     */
    public static String arrayToString(String[] array) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < array.length; i++) {
            sb.append(stuffString(array[i]));
            if (i < array.length - 1)
                sb.append("\"\\\"");
        }
        return sb.toString();
    }

    private static String stuffString(String str) {
        StringBuffer sb = new StringBuffer(str);
        int charsInserted = 0;
        int foundIndex1 = str.indexOf("\"", 0);
        int foundIndex2 = str.indexOf("\\", 0);
        int foundIndex = -1;
        if (foundIndex1 > -1 && foundIndex1 < foundIndex2)
            foundIndex = foundIndex1;
        else
            foundIndex = foundIndex2;
        while (foundIndex > -1) {
            sb.insert(foundIndex + charsInserted, "\\");
            charsInserted = charsInserted + 1;
            foundIndex1 = str.indexOf("\"", ++foundIndex);
            foundIndex2 = str.indexOf("\\", foundIndex);
            if (foundIndex1 > -1 && (foundIndex1 < foundIndex2 || foundIndex2 == -1))
                foundIndex = foundIndex1;
            else
                foundIndex = foundIndex2;
        }
        return sb.toString();
    }
}

Related

  1. arrayToString(String[] array)
  2. arrayToString(String[] array)
  3. arrayToString(String[] array)
  4. arrayToString(String[] array)
  5. arrayToString(String[] array)
  6. arrayToString(String[] array)
  7. arrayToString(String[] array, int start, String delimiter)
  8. arrayToString(String[] array, String delim, boolean quotes)
  9. arrayToString(String[] array, String separator)