Java String split String by a given delimiter
//package com.demo2s; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { public static void main(String[] argv) throws Exception { String list = "demo2s.com,demo2s.com,demo2s.com,demo2s.com"; char delimiter = ','; System.out.println(java.util.Arrays.toString(parseDelimitedList(list, delimiter))); }//from w ww .j a va 2 s .c o m /** * Parse a list of substrings separated by a given delimiter. The delimiter * can also appear in substrings (just double them): * * parseDelimitedString("this|is", '|') returns ["this","is"] * parseDelimitedString("this||is", '|') returns ["this|is"] * * @param list String containing delimited substrings * @param delimiter Delimiter (anything except ' ' is allowed) * * @return String[] A String array of parsed substrings */ public static String[] parseDelimitedList(String list, char delimiter) { String delim = "" + delimiter; StringTokenizer st = new StringTokenizer(list + delim + " ", delim, true); ArrayList<String> v = new ArrayList<String>(); String lastToken = ""; String word = ""; while (st.hasMoreTokens()) { String tok = st.nextToken(); if (lastToken != null) { if (tok.equals(delim)) { word = word + lastToken; if (lastToken.equals(delim)) tok = null; } else { if (!word.equals("")) v.add(word); word = ""; } } lastToken = tok; } return v.toArray(new String[0]); } }