我正在尝试将多行字符串中的Unix风格的行尾(LF
(转换为Windows风格的(CR LF
(。
我的攻击计划是:
- 将所有
CR LF
实例替换为LF
- 然后将所有
LF
实例替换为CR LF
但是,此代码片段与"rn"
不匹配:
String test = "testrncase";
test.replaceAll("rn","n");
PrintWriter testFile = new PrintWriter("test.txt");
testFile.print(test);
testFile.close();
我已经尝试过使用双/三/四反斜杠。没有骰子。
我还知道test
字符串不包含文字rn
,因为它在打印到文件时将它们检测为CR LF
。
我在这里错过了什么?
你没有从你的代码中获取修改后的字符串。
字符串是不可变的,因此您需要保存 replaceAll
的返回值。没有方法可以更改String
的实例
String test = "testrncase";
//Print the character before
for(char c : test.toCharArray()){ System.out.print((int)c + " ");};
System.out.println();
//Save the replace result
test = test.replaceAll("rn","n");
//Print the character after
for(char c : test.toCharArray()){ System.out.print((int)c + " ");};
表明测试首先未更改然后更改
116 101 115 116 13 10 99 97 115 101 //BEFORE
116 101 115 116 10 99 97 115 101 //AFTER