Here you can find the source of split(String content)
Parameter | Description |
---|---|
content | the content to split |
public static String[] split(String content)
//package com.java2s; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { /**// w w w .j a v a 2s. c o m * Split the given content by comma. However if a part of the content is in quotes, that part should not be split if * it contains any commas. For example foo,bar will be returned as an array of length 2; "foo,bar" will be returned * as an array of 1. * * @param content the content to split * @return the array containing individual parts of the content */ public static String[] split(String content) { content = content.trim(); int idx = content.indexOf(','); if (idx < 0) { return new String[] { content }; } else if (content.indexOf('"') < 0) { return content.split("\\,", -1); } else { List<String> parts = new ArrayList<>(); while (true) { idx = content.indexOf(','); int quote = content.indexOf('"'); int quote2 = content.indexOf('"', quote + 1); if (quote > -1 && quote2 < 0) { // something is wrong - only one quote return null; } else if (quote < 0) { parts.addAll(Arrays.asList(content.split("\\,", -1))); break; } if (quote < idx) { // started with a quote parts.add(content.substring(1, quote2).trim()); } else if (quote > idx) { // quoted part is in between String firstPart = content.substring(0, quote - 1).trim(); parts.addAll(Arrays.asList(firstPart.split("\\,", -1))); String secondPart = content.substring(quote + 1, quote2).trim(); parts.add(secondPart); } if (content.length() > quote2 + 1) { content = content.substring(quote2 + 1).trim(); if (content.charAt(0) == ',') { content = content.substring(1); } else { return null; } } else { break; } } return parts.toArray(new String[parts.size()]); } } /** * Trim the data of leading and trailing quotes and white spaces. * * @param value the value to trim * @return trimmed value */ private static String trim(String valueToTrim) { String value = valueToTrim.trim(); if (!value.isEmpty() && value.charAt(0) == '"') { value = value.substring(1, value.length() - 1).trim(); } return value; } }