split the given string into different tokens at the occurrence of specified delimiter - Java java.lang

Java examples for java.lang:String Split

Description

split the given string into different tokens at the occurrence of specified delimiter

Demo Code


import java.security.MessageDigest;

public class Main{
    public static void main(String[] argv){
        String str = "java2s.com";
        String delimeter = ".";
        System.out.println(java.util.Arrays.toString(getTokensArray(str,delimeter)));
    }/*ww w.j av  a 2s . com*/
    /**  
     * This method is used to split the given string into different tokens at  
     * the occurrence of specified delimiter  
     *  
     * @param str The string that needs to be broken  
     * @param delimeter The delimiter used to break the string  
     * @return a string array  
     */

    public static String[] getTokensArray(String str, String delimeter) {
        String[] data;
        if (str == null) {
            return null;
        }

        if (delimeter == null || "".equals(delimeter) || "".equals(str)) {
            data = new String[1];
            data[0] = str;
            return data;
        } else {
            StringTokenizer st = new StringTokenizer(str, delimeter);
            int tokenCount = st.countTokens();
            data = new String[tokenCount];
            for (int i = 0; st.hasMoreTokens(); i++) {
                data[i] = st.nextToken();
            }
            return data;
        }
    }
    public static String toString(Exception e) {

        StringWriter s = new StringWriter();
        e.printStackTrace(new PrintWriter(s));
        return s.toString();
    }
}

Related Tutorials