如何在Android中的字符串中插入新行

Ree*_*eed 55 string android enter

这可能看起来像一个愚蠢的问题,但我一直在寻找,无法找到答案.

我正在创建一个Android应用程序,其中有一个按钮,它将在电子邮件中发送一些信息,我不希望所有内容都在一个段落中.

这是我的应用程序为电子邮件正文的putExtra所做的事情:

I am the first part of the info being emailed. I am the second part. I am the third part.
Run Code Online (Sandbox Code Playgroud)

这就是我想要它做的事情:

I am the first part of the info being emailed.
I am the second part.

I am the third part.
Run Code Online (Sandbox Code Playgroud)

如何将新行放入字符串或使用putExtra方法来实现?

谢谢.

小智 82

尝试:

String str = "my string \n my other string";
Run Code Online (Sandbox Code Playgroud)

打印时,您将获得:

my string
my other string


ken*_*eno 75

尝试使用System.getProperty("line.separator")获取新行.

  • 另外,我学会了将\n放在一个字符串中插入一个新行 (15认同)
  • @Jakar`System.getProperty("line.separator")`是独立于平台的,而`\n`则不是.但是,如果你正在开发Android应用程序,平台是固定的,linux/android使用`\n`作为换行符.[维基百科/换行(https://en.wikipedia.org/wiki/Newline) (2认同)
  • @wischi,好点.并且`\ r \n`更符合跨系统兼容性(如果我错了,请纠正我),因此更适合传输数据.例如,如果您使用`\n`发送电子邮件并在使用`\ r \n`的系统上读取它,则可能会丢失行,而在大多数情况下,如果您将`\ r \n`传递给想要的系统只是`\n`,它会补偿.我可能在这里错了,我没有来源.这正是我随着时间的推移而收集的. (2认同)

Ari*_*Roy 19

我个人更喜欢使用" \n ".这只是在Linux或Android中进行换行.

例如,

String str = "I am the first part of the info being emailed.\nI am the second part.\n\nI am the third part.";
Run Code Online (Sandbox Code Playgroud)

产量

I am the first part of the info being emailed.
I am the second part.

I am the third part.
Run Code Online (Sandbox Code Playgroud)

一种更通用的方式是使用,

System.getProperty("line.separator")
Run Code Online (Sandbox Code Playgroud)

例如,

String str = "I am the first part of the info being emailed." + System.getProperty("line.separator") + "I am the second part." + System.getProperty("line.separator") + System.getProperty("line.separator") + "I am the third part.";
Run Code Online (Sandbox Code Playgroud)

带来与上面相同的输出.这里,类的静态getProperty()方法System可用于获取line.seperator特定OS 的" ".

但这根本不是必需的,因为这里的操作系统是固定的,即Android.因此,每次调用一个方法都是一项繁重且不必要的操作.

此外,这也会增加您的代码长度并使其看起来有点混乱."\n"是甜蜜而简单的.


Mar*_*rco 8

<br>CDATA标签中使用。例如,我的 strings.xml 文件包含这样一个项目:

<item><![CDATA[<b>My name is John</b><br>Nice to meet you]]></item>
Run Code Online (Sandbox Code Playgroud)

和版画

My name is John
Nice to meet you
Run Code Online (Sandbox Code Playgroud)