2010-11-22 39 views
2

如何附加「\ n」,從字面上看,不像特殊字符。如何附加字面上與StringBuffer?

我不會來實現這一目標:

StringBuffer st = new StringBuffer; 

st.append(text1); 
st.append("\n"); 
st.append(text2); 

和輸出字符串是:

text1 \n text2 

text1 
text2 

回答

13
StringBuffer st = new StringBuffer(); 
st.append("Hello"); 
st.append("\\n"); //<- the first \ escapes the second 
st.append("World"); 
3
st.append("\\n"); 
2

逃亡「\」與其他\:

st.append(" \\n "); 
4

您需要轉義反斜線,如果你想打印一個反斜槓:

st.append("\\n"); 
1

你要逃離逃離符號\。這意味着你必須追加"\\n"

1

如果不需要同步並且需要轉義特殊字符(如前面其他答案中提到的),請檢查以使用StringBuilder以獲得更好的性能。

相關問題