Java String Chomp chomp(String str)

Here you can find the source of chomp(String str)

Description

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

License

Open Source License

Parameter

Parameter Description
str the String to chomp a newline from, may be null

Declaration

public static String chomp(String str) 

Method Source Code

//package com.java2s;

public class Main {
    /**//www.  j ava  2s .  c  om
     * 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

  1. chomp(String sd, String c)
  2. chomp(String str)
  3. chomp(String str)
  4. chomp(String str)
  5. chomp(String str)
  6. chomp(String str, String sep)
  7. chomp(String str, String separator)
  8. chomp(String value)
  9. chomp(StringBuilder sb)