This is a simple utility to split strings. - Java java.lang

Java examples for java.lang:String Split

Introduction

The following code shows how to This is a simple utility to split strings. .

Demo Code

//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        String sString = "java2s.com";
        boolean bIgnoreQuotes = true;
        System.out.println(java.util.Arrays.toString(split(sString,
                bIgnoreQuotes)));// w w  w. ja v a2s  .co  m
    }

    /**
     * This is a simple utility to split strings.
     * The string is splitted following these rules (in the order):
     * <ul>
     * <li>If a single quote (') or a double quote (") is found at the start of the word, the split will
     * occour at the next quote or double quote
     * <li>Otherwise, the split occurres as soon as a space is found.
     * </ul>
     * @param sString The string to split
     * @param bIgnoreQuotes For future implementation
     * @return The splitted string
     * 
     * @since JNRPE Server 1.04
     */
    public static String[] split(String sString, boolean bIgnoreQuotes) {
        List vRes = new ArrayList();
        char splitChar = ' ';
        char[] vChars = sString.trim().toCharArray();

        StringBuffer sbCurrentToken = new StringBuffer();

        for (int i = 0; i < vChars.length; i++) {
            if (vChars[i] == splitChar) {
                if (sbCurrentToken.toString().length() != 0) {
                    vRes.add(sbCurrentToken.toString());
                    sbCurrentToken = new StringBuffer();
                    splitChar = ' ';

                }
                continue;
            }

            switch (vChars[i]) {
            case '"':
            case '\'':
                if (sbCurrentToken.length() == 0 && splitChar == ' ') {
                    splitChar = vChars[i];
                    break;
                }
            default:
                sbCurrentToken.append(vChars[i]);
            }
        }

        if (sbCurrentToken.length() != 0)
            vRes.add(sbCurrentToken.toString());

        String[] vRet = new String[vRes.size()];

        for (int i = 0; i < vRet.length; i++)
            vRet[i] = (String) vRes.get(i);

        return vRet;
    }
}

Related Tutorials