Java CSV String Create toCSVString(String s)

Here you can find the source of toCSVString(String s)

Description

to CSV String

License

Apache License

Parameter

Parameter Description
s a parameter

Declaration

static String toCSVString(String s) 

Method Source Code

//package com.java2s;
/*//  w  w w. j  a  v a  2  s  .  co m
 *  * Copyright 2016 Skymind, Inc.
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *        http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 */

public class Main {
    /**
     *
     * @param s
     * @return
     */
    static String toCSVString(String s) {
        StringBuilder sb = new StringBuilder(s.length() + 1);
        sb.append('\'');
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            switch (c) {
            case '\0':
                sb.append("%00");
                break;
            case '\n':
                sb.append("%0A");
                break;
            case '\r':
                sb.append("%0D");
                break;
            case ',':
                sb.append("%2C");
                break;
            case '}':
                sb.append("%7D");
                break;
            case '%':
                sb.append("%25");
                break;
            default:
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

Related

  1. toCSVBuffer(byte barr[])
  2. toCsvLine(final String[] parts)
  3. toCSVString(double[] d)
  4. toCsvString(Object object)
  5. toCSVString(Object[] pStringArray)
  6. toCsvString(String text, char separator, char quote, String quoteEscaped)
  7. toCsvString(String text, String splitString, String replaceSplitChar)
  8. toCSVString(String[] fields)