trims the string and reduces consecutive white spaces to only one space Example: " a a " --> "a a" - Java java.lang

Java examples for java.lang:String Trim

Description

trims the string and reduces consecutive white spaces to only one space Example: " a a " --> "a a"

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(removeExtraSpace(str));
    }//from w w w  .  jav a2  s . c  o  m

    /**
     * trims the string and reduces consecutive white spaces to only one space
     * Example: " a   a  " --> "a a"
     * @return processed string, returns null if parameter is null
     */
    public static String removeExtraSpace(String str) {
        if (str == null) {
            return null;
        }

        return str.trim().replaceAll("\\s+", " ");

    }
}

Related Tutorials