java 字符串原样输出

y234239150 2010-08-12 11:53:02
String str = "aaa\nnn\tttt" + System.getProperty("line.separator") + "rrr";
这个字符串怎么样能在控制台原样输出?
就是说输出的是aaa\nnn\tttt\r\nrrr
而不是输出
aaa
nn ttt

rrr
有几种实现呢?
...全文
518 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
y234239150 2010-08-12
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 amkio 的回复:]
String str = "aaa\nnn\tttt" + System.getProperty("line.separator") + "rrr";
String str2 = str.replaceAll("\", "\\");
[/Quote]
在eclipse下String str2 = str.replaceAll("\", "\\");这么写会直接编译不过去!
String str2 = str.replaceAll("\\", "\\\\");这么写会报异常。。要用replace
而用replace又没有效果。。。
撞撞小屁股 2010-08-12
  • 打赏
  • 举报
回复
String str = "aaa\nnn\tttt" + System.getProperty("line.separator") + "rrr";
String str2 = str.replaceAll("\", "\\");
y234239150 2010-08-12
  • 打赏
  • 举报
回复
汗。。。如果是从文件中读出来的一行字符串,中间包含制表符换行回车啥的,就不能直接\\了。。
dr_lou的方式可以,
还有别的方式么?
dr_lou 2010-08-12
  • 打赏
  • 举报
回复
str.replaceAll("\n", "\\\\n").replaceAll("\t", "\\\\t")

System.getProperty("line.separator") 似乎还是有影响。
dqsweet 2010-08-12
  • 打赏
  • 举报
回复
aaa\\nnn\\tttt\\r\\nrrr
撞撞小屁股 2010-08-12
  • 打赏
  • 举报
回复
String str = "aaa\\nnn\\tttt" + System.getProperty("line.separator") + "rrr";
pzhxpzhx 2010-08-12
  • 打赏
  • 举报
回复

public class Test {
public static void main(String args[]){
String str = "aaa\nnn\tttt" + System.getProperty("line.separator") + "rrr";
for(int i=0; i<str.length();i++){
if(str.charAt(i)=='\n'){
System.out.print("\\n");}
else if(str.charAt(i)=='\t'){
System.out.print("\\t");}
else if(str.charAt(i)=='\r'){
System.out.print("\\r");}
else
System.out.print(str.charAt(i));
}
}
}
撞撞小屁股 2010-08-12
  • 打赏
  • 举报
回复


String str = "aaa\nnn\tttt" + System.getProperty("line.separator") + "rrr";

int k = 0 ;
for(int i=0; i<str.length();i++){
char c = str.charAt(i) ;
if (c ==9 || c==10 || c==13){
k++ ;
}

}
char[] carray = new char[str.length() + k];
int j= 0 ;
for(int i=0; i<str.length();i++){
char c = str.charAt(i) ;
if (c == 9){
carray[j++] = (char)92;
carray[j++] = (char)116;
continue;
}
if (c == 10){
carray[j++] = (char)92;
carray[j++] = (char)110;
continue;
}
if (c == 13){
carray[j++] = (char)92;
carray[j++] = (char)114;
continue;
}
carray[j++] = c;
}

System.out.println(carray);

51,396

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧