Java examples for java.lang:String Replace
replaces all occurrences of the CR character with the LF character, except when the CR is immediately followed by a LF (CRLF sequences), in which case the CR is removed.
/*//from w ww.j a v a 2 s. com * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2013 Jaspersoft Corporation. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ /* * Contributors: * Gaganis Giorgos - gaganis@users.sourceforge.net */ //package com.java2s; public class Main { public static void main(String[] argv) { String text = "java2s.com"; System.out.println(replaceCRwithLF(text)); } /** * This method replaces all occurrences of the CR character with the LF character, * except when the CR is immediately followed by a LF (CRLF sequences), in which case the CR is removed. */ public static String replaceCRwithLF(String text) { if (text != null) { int length = text.length(); char[] chars = text.toCharArray(); int r = 0; boolean dirty = false; for (int i = 0; i < length; ++i) { char ch = chars[i]; if (ch == '\r') { dirty = true; if (i + 1 < length && chars[i + 1] == '\n') { r++; } else { chars[i - r] = '\n'; } } else { chars[i - r] = ch; } } return dirty ? new String(chars, 0, length - r) : text; } return null; } }