如何将java字符串中的空格字符替换为反斜杠?
我试过这个:
String text = " 1 2 3 4 5 6 7 8 9 10";
text = text.replace(" ","\\");
System.out.println(text2);但请看一下eclipse调试变量中的结果:
text 1 2 3 4 5 6 7 8 9 10
text2 \\1\\2\\3\\4\\5\\6\\7\\8\\9\\10但在我的日志中,结果是不同的:
07-18 14:56:31.049: I/System.out(9177): \1\2\3\4\5\6\7\8\9\10我想将它与smb命令一起使用,以便在目录文件名中留出空格。当我在我的代码中手动设置它时,这个命令起作用。结果应该是这样的:
source : smb://192.168.0.254/Disque dur/
text = text.replace(" ","\040");
result : smb://192.168.0.254/Disque\040dur/但是当我使用replace()方法时,出现了双反斜杠...
result : smb://192.168.0.254/Disque\\040dur/
07-18 15:15:10.439: E/Home(9538): jcifs.smb.SmbException: The network name cannot be found.感谢你的帮助
发布于 2013-07-18 21:30:33
如下所示:
String text = " 1 2 3 4 5 6 7 8 9 10";
text = text.replace(" ","\\\\");
System.out.println(text2);前面有反斜杠()的字符是转义序列,对编译器有特殊的意义。'\‘此时在文本中插入一个反斜杠字符。
你可以在这里阅读更多内容:http://docs.oracle.com/javase/tutorial/java/data/characters.html
发布于 2013-07-18 21:32:36
在Java中,反斜杠需要转义。查看此link
\在文本中插入反斜杠字符。
\\ -表示\。
\\\\ -表示\\。
不要让控制台欺骗了你,你所看到的实际上只有一个\。
发布于 2013-07-18 21:39:29
您还可以像这样删除空格
String mysz = " 1 2 3 4 5 6 7 8 9 10";
String mysz2 = mysz.replaceAll("\\s","");
System.out.println(""+mysz2);https://stackoverflow.com/questions/17724714
复制相似问题