StringUtils.java Source code

Java tutorial

Introduction

Here is the source code for StringUtils.java

Source

/**
 * <pre>
 * Utilitaire de gestion des chaines de caractres.
 * </pre>
 * @version $Date: 2005/07/20 10:59:20 $, $Revision: 1.2 $, branche-$Name:  $  
 * @author $Author: mlo $
 */
public class StringUtils {
    /**
     * enlever des caractres de la partie gauche
     * @param str chaine source
     * @param patern chaine  enlever
     * @param ignoreCase ignorer MIN/MAJ du patern
     * @return chaine rsultat
     */
    public static String ltrim(String toTrim, String patern, boolean ignoreCase) {
        if (!ignoreCase) {
            return fastLtrim(toTrim, patern);
        }
        patern = (patern == null) ? "" : patern;
        String str = (toTrim == null) ? "" : toTrim;
        int start = 0;
        if (!ignoreCase) {
            if (str.equalsIgnoreCase(patern)) {
                return "";
            }
            while (true) {
                if ((str.length() - start) < patern.length()) {
                    break;
                }
                if (str.substring(start, start + patern.length()).equalsIgnoreCase(patern)) {
                    start += patern.length();
                } else {
                    break;
                }
            }
        }
        return str.substring(start);
    }

    /**
     * enlever des caractres de la partie droite
     * @param toTrim chaine source
     * @param patern chaine  enlever
     * @param ignoreCase ignorer MIN/MAJ du patern
     * @return chaine rsultat
     */
    public static String rtrim(String toTrim, String patern, boolean ignoreCase) {
        if (!ignoreCase) {
            return fastRtrim(toTrim, patern);
        }
        patern = (patern == null) ? "" : patern;
        String str = (toTrim == null) ? "" : toTrim;
        int end = str.length();
        if (!patern.equals("") && !str.equals("")) {
            while (true) {
                if ((end - patern.length()) < 0) {
                    break;
                }
                if (str.substring(end - patern.length(), end).equalsIgnoreCase(patern)) {
                    end -= patern.length();
                } else {
                    break;
                }
            }
        }
        return str.substring(0, end);
    }

    private static String fastLtrim(String toTrim, String pattern) {
        if (toTrim == null || pattern == null || pattern.equals("") || !toTrim.startsWith(pattern)) {
            return toTrim;
        }
        return fastLtrim(toTrim.substring(pattern.length()), pattern);
    }

    private static String fastRtrim(String toTrim, String pattern) {
        if (toTrim == null || pattern == null || pattern.equals("") || !toTrim.endsWith(pattern)) {
            return toTrim;
        }
        return fastRtrim(toTrim.substring(0, toTrim.length() - pattern.length()), pattern);
    }

}