我如何替换所有的换行符从一个字符串在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", "");
但这似乎并不奏效。
如何做到这一点呢?
当前回答
可以使用泛型方法用任意字符替换任意字符。
public static void removeWithAnyChar(String str, char replceChar,
char replaceWith) {
char chrs[] = str.toCharArray();
int i = 0;
while (i < chrs.length) {
if (chrs[i] == replceChar) {
chrs[i] = replaceWith;
}
i++;
}
}
其他回答
换行符在windows/linux/mac下是不一样的。你应该使用系统。使用属性line.separator获取properties。
试着这样做:
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", "");
String text = readFileAsString("textfile.txt").replace("\n","");
.replace返回一个新字符串,Java中的字符串是不可变的。
str = str.replaceAll("\\r\\n|\\r|\\n", " ");
在搜索了很多之后,完美地为我工作,在其他每一行都失败了。
可以使用泛型方法用任意字符替换任意字符。
public static void removeWithAnyChar(String str, char replceChar,
char replaceWith) {
char chrs[] = str.toCharArray();
int i = 0;
while (i < chrs.length) {
if (chrs[i] == replceChar) {
chrs[i] = replaceWith;
}
i++;
}
}