Saturday, May 9, 2009

Code : How to split String

Code While programming it may requires to split the string into words, to accomplish this one can use ‘StringUtilities’ class like :

StringUtilities su = null;
String[] abc = su.stringToWords("Xyz XYZ xyz xyZ");

Output : abc[0] = “Xyz”, abc[1] = “XYZ”, abc[2] = “xyz”, abc[3] = “xyZ”.

Or you can use following helper method to do the same :

public static final String[] splitString(final String data,
     final char splitChar, final boolean allowEmpty) {
    Vector v = new Vector();
    int indexStart = 0;
    int indexEnd = data.indexOf(splitChar);
    if (indexEnd != -1) {
        while (indexEnd != -1) {
            String s = data.substring(indexStart, indexEnd);
            if (allowEmpty || s.length() > 0) {
                    v.addElement(s);
            }
            indexStart = indexEnd + 1;
            indexEnd = data.indexOf(splitChar, indexStart);
         }

         if (indexStart != data.length()) {
            // Add the rest of the string
            String s = data.substring(indexStart);
            if (allowEmpty || s.length() > 0) {
                 v.addElement(s);
            }
          }

    } else {
         if (allowEmpty || data.length() > 0) {
             v.addElement(data);
         }
    }

    String[] result = new String[v.size()];
    v.copyInto(result);
    return result;
}

It has the ability to skip any blank lines ( typically split on \n), so it also has the ability to remove any blank sequences it encounters.

No comments:

Post a Comment

Place your comments here...