Java String remove white spaces
//package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { String str = " de mo2s .c o m"; System.out.println(deleteWhitespace(str)); }/*from w ww. j av a 2 s. com*/ /** * <p> * Deletes all whitespaces from a String as defined by * {@link Character#isWhitespace(char)}. * </p> * * <pre> * deleteWhitespace(null) = null * deleteWhitespace("") = "" * deleteWhitespace("abc") = "abc" * deleteWhitespace(" ab c ") = "abc" * </pre> * * @param str * the String to delete whitespace from, may be null * @return the String without whitespaces, <code>null</code> if null String * input */ public static String deleteWhitespace(String str) { if (isEmpty(str)) { return str; } int sz = str.length(); char[] chs = new char[sz]; int count = 0; for (int i = 0; i < sz; i++) { if (!Character.isWhitespace(str.charAt(i))) { chs[count++] = str.charAt(i); } } if (count == sz) { return str; } return new String(chs, 0, count); } /** * <p> * Checks if a String is empty ("") or null. * </p> * * <pre> * isEmpty(null) = true * isEmpty("") = true * isEmpty(" ") = false * isEmpty("bob") = false * isEmpty(" bob ") = false * </pre> * * <p> * NOTE: This method changed in Lang version 2.0. It no longer trims the String. * That functionality is available in isBlank(). * </p> * * @param str * the String to check, may be null * @return <code>true</code> if the String is empty or null */ public static boolean isEmpty(String str) { return str == null || str.length() == 0; } } /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */