我如何替换所有的换行符从一个字符串在Java在这样的方式,将工作在Windows和Linux(即没有具体的操作系统的回车/换行/新行等问题)?
我尝试过(注意readFileAsString是一个将文本文件读入String的函数):
String text = readFileAsString("textfile.txt");
text.replace("\n", "");
但这似乎并不奏效。
如何做到这一点呢?
我如何替换所有的换行符从一个字符串在Java在这样的方式,将工作在Windows和Linux(即没有具体的操作系统的回车/换行/新行等问题)?
我尝试过(注意readFileAsString是一个将文本文件读入String的函数):
String text = readFileAsString("textfile.txt");
text.replace("\n", "");
但这似乎并不奏效。
如何做到这一点呢?
当前回答
试着这样做:
textValue= textValue.replaceAll("\n", "");
textValue= textValue.replaceAll("\t", "");
textValue= textValue.replaceAll("\\n", "");
textValue= textValue.replaceAll("\\t", "");
textValue= textValue.replaceAll("\r", "");
textValue= textValue.replaceAll("\\r", "");
textValue= textValue.replaceAll("\r\n", "");
textValue= textValue.replaceAll("\\r\\n", "");
其他回答
该函数将所有空格(包括换行符)归一化为单个空格。不完全是最初的问题所要求的,但在许多情况下可能恰恰是需要的:
import org.apache.commons.lang3.StringUtils;
final String cleansedString = StringUtils.normalizeSpace(rawString);
换行符在windows/linux/mac下是不一样的。你应该使用系统。使用属性line.separator获取properties。
String text = readFileAsString("textfile.txt").replaceAll("\n", "");
尽管在oracle网站中trim()的定义是 返回字符串的副本,省略前导和尾随空格。
文档没有说明新的行字符(前导和后尾)也将被删除。
简而言之 字符串文本= readFileAsString("textfile.txt").trim();对你也有用。 (用java6核对)
我发现奇怪的是(Apache) StringUtils还没有在这里被覆盖。
您可以使用.replace方法从字符串中删除所有换行符(或任何其他出现的子字符串)
StringUtils.replace(myString, "\n", "");
这一行将用空字符串替换所有换行符。
因为换行符在技术上是一个字符,你可以选择使用. replacecars方法来替换字符
StringUtils.replaceChars(myString, '\n', '');
试着这样做:
textValue= textValue.replaceAll("\n", "");
textValue= textValue.replaceAll("\t", "");
textValue= textValue.replaceAll("\\n", "");
textValue= textValue.replaceAll("\\t", "");
textValue= textValue.replaceAll("\r", "");
textValue= textValue.replaceAll("\\r", "");
textValue= textValue.replaceAll("\r\n", "");
textValue= textValue.replaceAll("\\r\\n", "");