get Clean String List from comma separated string - Java java.lang

Java examples for java.lang:String New Line

Description

get Clean String List from comma separated string

Demo Code


//package com.java2s;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        String kommaSeparatedString = "b,    oo,  k2s , com";
        System.out.println(getCleanStringList(kommaSeparatedString));
    }//from  w  w  w.  j a  v  a 2s  . c o m

    public static List<String> getCleanStringList(
            String kommaSeparatedString) {
        return getStringList(removeNewlinesTabsAndSpaces(
                kommaSeparatedString).split(","));
    }

    public static List<String> getStringList(String[] stringArray) {
        return Arrays.asList(stringArray);
    }

    private static String removeNewlinesTabsAndSpaces(String input) {
        String output = input;

        //remove newlines
        output = output.replaceAll("\n", "");
        output = output.replaceAll("\r", "");

        //remove tabs
        output = output.replace("\t", "");

        //remove whitespace before and after a comma
        output = output.replaceAll("( *)(,)( *)", "$2");

        //remove whitespace before and after the string, and return it
        return output.trim();
    }
}

Related Tutorials