我需要显示一个包含很多新行'\ n'的字符串。这些字符串需要替换为该字符串中的实际换行符。我怎么能在android中做到这一点?
答案 0 :(得分: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
将分开打印。
答案 1 :(得分:0)
String myString = "lots of \n new \n lines";
String newStringWithoutNewLines = myString.replace("\n", "");
答案 2 :(得分: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?"
然后将它们连接起来
答案 3 :(得分:0)
似乎正在发生的事情是,您从数据库收到的字符串不包含换行符,而是包含字符\
和n
。最简单的解决方法是使用String.replace
函数将字符序列\
n
替换为字符\n
,如下所示:
String str = getStringWithFakeNewlines();
str.replace("\\n", "\n"); // The first backslash is doubled to find actual backslashes