Trim all whitespace from the given String: leading, trailing, and inbetween characters. - Java java.lang

Java examples for java.lang:String Trim

Introduction

The following code shows how to Trim all whitespace from the given String: leading, trailing, and inbetween characters. .

Demo Code

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;

public class Main{
    public static void main(String[] argv){
        String str = "   java2s.com  ";
        System.out.println(trimAllWhitespace(str));
    }// w w  w. jav a  2 s .  com
    /**
     * Trim <i>all</i> whitespace from the given String: leading, trailing, and
     * inbetween characters.
     * 
     * @param str
     *            the String to check
     * @return the trimmed String
     * @see java.lang.Character#isWhitespace
     */
    public static String trimAllWhitespace(String str) {
        if (!hasLength(str)) {
            return str;
        }
        StringBuilder sb = new StringBuilder(str);
        int index = 0;
        while (sb.length() > index) {
            if (Character.isWhitespace(sb.charAt(index))) {
                sb.deleteCharAt(index);
            } else {
                index++;
            }
        }
        return sb.toString();
    }
}

Related Tutorials