Java CSV String Create toCSVString(String[] fields)

Here you can find the source of toCSVString(String[] fields)

Description

to CSV String

License

Open Source License

Declaration

public static String toCSVString(String[] fields) 

Method Source Code

//package com.java2s;

public class Main {
    public static String toCSVString(String[] fields) {
        StringBuilder b = new StringBuilder();
        for (String fld : fields) {
            if (b.length() > 0) {
                b.append(',');
            }/*w  w  w.j  a v a  2  s.  c  o  m*/
            String field = escapeString(fld, new char[] { '\"' }, '\"'); // escape quotes with double quotes
            b.append('\"').append(field).append('\"');
        }
        return b.toString();
    }

    public static String escapeString(String s, char[] charsToEscape,
            char escapeChar) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == escapeChar) {
                result.append(escapeChar);
            } else {
                for (char charToEscape : charsToEscape) {
                    if (c == charToEscape) {
                        result.append(escapeChar);
                        break;
                    }
                }
            }
            result.append(c);
        }
        return result.toString();
    }
}

Related

  1. toCsvString(Object object)
  2. toCSVString(Object[] pStringArray)
  3. toCSVString(String s)
  4. toCsvString(String text, char separator, char quote, String quoteEscaped)
  5. toCsvString(String text, String splitString, String replaceSplitChar)