Remove all whitespace from the start and end of a string. - Java java.lang

Java examples for java.lang:String End

Description

Remove all whitespace from the start and end of a string.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(chomp(str));
    }//from  w w w  . j av  a2 s  . co  m

    /**
     * Remove all whitespace from the start and end of a string. Removes
     * space, cr, lf, and tab.
     *
     *
     * @param str  the String to chomp a newline from, may be null
     */
    public static String chomp(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }

        int firstIdx = 0;
        int lastIdx = str.length() - 1;

        char c = str.charAt(lastIdx);
        while (c == '\n' || c == '\r' || c == '\t' || c == ' ') {
            if (lastIdx == 0) {
                break;
            }
            lastIdx--;
            c = str.charAt(lastIdx);
        }

        c = str.charAt(firstIdx);
        while (c == '\n' || c == '\r' || c == '\t' || c == ' ') {
            firstIdx++;
            if (firstIdx >= lastIdx) {
                break;
            }
            c = str.charAt(firstIdx);
        }

        return str.substring(firstIdx, lastIdx + 1);
    }
}

Related Tutorials