1

我需要显示一个包含很多换行符'\n'的字符串。这些需要替换为该字符串中的实际换行符。我怎么能在android中做到这一点?

4

4 回答 4

1

你可以用这个..

StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter, true);
writer.println("line1");
writer.println("line2");
writer.println("line3");
useString(stringWriter.toString());

line1, line2 and line3将打印在单独的行中。

于 2014-08-05T07:10:03.847 回答
0
String myString = "lots of \n new \n lines";
String newStringWithoutNewLines = myString.replace("\n", "");
于 2013-04-26T01:23:48.860 回答
0

似乎正在发生的是您从数据库收到的字符串不包含换行符,而是包含字符\n. 最简单的解决方法是简单地使用String.replace函数将字符序列替换为字符\ n\n如下所示:

String str = getStringWithFakeNewlines();
str.replace("\\n", "\n"); // The first backslash is doubled to find actual backslashes
于 2013-04-26T02:00:36.877 回答
0

你应该像这样连接换行符:

String str = "This is testing" + "\n" + "How are you?";

你从数据库中说你可以像这样拆分:

String[] separated = str.split("\n");
separated[0]; // this will contain "This is testing"
separated[1]; // this will contain "How are you?"

然后将它们连接起来

于 2013-04-26T01:38:25.643 回答