Breaking News

Saturday 5 April 2014

Split String depending on delimiter in java

To Split a String with delimiter condition and form an array of string

Considering a scenario where in we have read a line from csv or xls file in the form of string and need to separate the columns in array of string depending on delimiters.


 Below is the code snippet to achieve this problem..

{
...
...
String line = new BufferedReader(new FileReader("your file"));

String[] splittedString = StringSplitToArray(stringLine,"\"");

}

public static String[] StringSplitToArray(String stringToSplit, String delimiter) {
         StringBuffer token = new StringBuffer();
         Vector tokens = new Vector();
         char[] chars = stringToSplit.toCharArray();
         for (int i=0; i  0) {
                     tokens.addElement(token.toString());
                     token.setLength(0);
                     i++;
                 }
             } else {
                 token.append(chars[i]);
             }
         }<br />
         if (token.length() &gt; 0) {
             tokens.addElement(token.toString());
         }
         // convert the vector into an array
         String[] preparedArray = new String[tokens.size()];
         for (int i=0; i &lt; preparedArray.length; i++) {
             preparedArray[i] = (String)tokens.elementAt(i);
         }
         return preparedArray;
}

Above code snippet contains method call to StringSplitToArray where in the method converts the stringline into string array splitting the line depending on the delimiter specified or passed to the method. Delimiter can be comma separator(,) or double code(").

No comments:

Post a Comment

Designed By