Java examples for java.lang:String Trim
trim But Keep Line Feeds
/*/*from w w w.j a v a 2 s . co m*/ You may freely copy, distribute, modify and use this class as long as the original author attribution remains intact. See message below. Copyright (C) 2004 Christian Pesch. All Rights Reserved. */ //package com.java2s; public class Main { public static void main(String[] argv) { String string = "java2s.com"; System.out.println(trimButKeepLineFeeds(string)); } public static String trimButKeepLineFeeds(String string) { if (string == null) return null; StringBuffer buffer = new StringBuffer(string); for (int i = 0; i < buffer.length(); i++) { char c = buffer.charAt(i); if (Character.isWhitespace(c) && c != '\r' && c != '\n') buffer.setCharAt(i, ' '); } return buffer.toString().trim(); } public static String trim(String string) { if (string == null) return null; StringBuffer buffer = new StringBuffer(string); for (int i = 0; i < buffer.length(); i++) { char c = buffer.charAt(i); if (Character.isWhitespace(c)) buffer.setCharAt(i, ' '); } return buffer.toString().trim(); } }