split String and get data before the criteria - Java java.lang

Java examples for java.lang:String Split

Description

split String and get data before the criteria

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String stringToSplit = "java2s.com";
        String splitCriteria = "o";
        boolean includeCriteria = true;
        boolean returnDataBeforeCriteria = true;
        System.out.println(splitString(stringToSplit, splitCriteria,
                includeCriteria, returnDataBeforeCriteria));
    }//from   www  . ja v a  2  s.  c  o  m

    public static String splitString(String stringToSplit,
            String splitCriteria, boolean includeCriteria,
            boolean returnDataBeforeCriteria) {
        String result = "";

        if (!isEmpty(stringToSplit) && !isEmpty(splitCriteria)) {
            //Set some stuff up for later use
            int position = stringToSplit.indexOf(splitCriteria);
            int criteriaLength = splitCriteria.length();

            if (position >= 0) {
                //Found the splitCriteria
                if (returnDataBeforeCriteria == true) {
                    //If you want to get all the data BEFORE splitCriteria
                    if (includeCriteria == true) {
                        result = stringToSplit.substring(0, position
                                + criteriaLength);
                    } else {
                        result = stringToSplit.substring(0, position);
                    }
                } else {
                    //If you want to get all the data AFTER splitCriteria
                    if (includeCriteria == true) {
                        result = stringToSplit.substring(position);
                    } else {
                        result = stringToSplit.substring(position
                                + criteriaLength);
                    }
                }
            } else {
                //If could NOT find splitCritera within stringToSplit, return
                //whole string as it was
                result = stringToSplit;
            }
        }

        return result;
    }

    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0);
    }

    public static int length(String source) {
        int result = 0;
        if (isNotEmpty(source)) {
            result = source.length();
        }
        return result;
    }

    public static String substring(String source, int offset, int dataLength) {
        StringBuilder sb = new StringBuilder();
        if (!isEmpty(source) && source.length() >= offset + dataLength) {
            sb.append(source.substring(offset, offset + dataLength));
        }
        return sb.toString();
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
}

Related Tutorials