text = Daily 10 am - 5 pm.\\nClosed Thanksgiving and Christmas.
private String activateNewlines( String text ) {
String temp = text;
if ( text.contains( "\\n") ) {
while ( temp.contains( "\\n" ) ) {
int index = temp.indexOf( "\\n" );
temp = temp.substring( 0, index ) + temp.substring( index + 1 );
}
return temp;
}
return text;
}
我试图去掉一个特殊字符的额外斜杠,但是由于某种原因,substring最终去掉了正斜杠。substring不喜欢字符串开头的斜杠吗?最后的字符串最终会变成
Daily 10 am - 5 pm.nClosed Thanksgiving and Christmas.
我需要的是
Daily 10 am - 5 pm.\nClosed Thanksgiving and Christmas.
编辑:最终为我工作的是:
String temp = text;
if ( text.contains( "\\n") ) {
temp = temp.replaceAll( "\\\\n", "\\\n" );
int x = 5;
return temp;
}
return text;
这实际上允许TextView识别换行符。
发布于 2012-08-29 02:12:27
我觉得你应该这么做,
string.replaceAll("\\n", "\n")
详细代码,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String text = "Daily 10 am - 5 pm.\\nClosed Thanksgiving and Christmas.";
Log.d("TEMP", "*********************************" + activateNewlines(text));
}
private String activateNewlines( String text ) {
String temp = text;
return temp.replaceAll("\\n", "\n");
}
Logcat输出是,
08-28 19:16:00.944: D/TEMP(9739): *********************************Daily 10 am - 5 pm.\nClosed Thanksgiving and Christmas.
发布于 2012-08-29 02:01:37
我有点糊涂了,但我要说的是。因此,"\n"
是一个新的行。"\\n"
是一个反斜杠和一个n,\n
。你可以只使用replaceAll来摆脱它:string.replaceAll("\n", "")
。这就是我困惑的地方,我不确定你到底想要什么。如果你想保留新行,那么你必须正确地从你获取它的地方获取它(例如,你应该获得一个\n
字符而不是转义版本)。
https://stackoverflow.com/questions/12169840
复制相似问题