Monthly Archives: September 2014

Trim string in Java

char
Don’t like string frameworks? Use POJO java!

static String trim(String value, char character) {
    if (value == null || value.isEmpty()) {
        return value;
    }
    String normalized = value.trim();

    int startIndex = 0;
    while (normalized.charAt(startIndex) == character) {
        startIndex++;
    }

    int endIndex = value.length() - 1;
    while (normalized.charAt(endIndex) == character) {
        endIndex--;
    }

    return normalized.substring(startIndex, endIndex + 1).trim();
}

Simple!