如何修剪字符串中的多行?

9bfwbjaz  于 2021-06-27  发布在  Java
关注(0)|答案(4)|浏览(250)

嗨,我们需要一个格式化的字符串为我们的应用程序。
预期产量:

Blow the candles real hard,
Coz now you have aged,
Don't pretend so much my dear,
Don't behave so sage,
Happy birthday to you,
Have a nice day,
Make the most of your day!

我想格式化一个字符串,如上所示,当我对字符串使用trim()函数时,它会给出如下结果

Blow the candles real hard,
 Coz now you have aged,
Don't pretend so much my dear,
 Don't behave so sage,
 Happy birthday to you,
 Have a nice day,
Make the most of your day!

我想删除每行开头的空格。我在下面使用了这些函数,它修剪了字符串的开头和结尾,但不修剪行。

poemText = poemText.trimMargin()
   poemText = poemText.trimIndent()
   poemText = poemText.replace("\n ", "\n")
   for(line in poemText.lines())
   {line.trim()}

感谢您的帮助

hl0ma9xz

hl0ma9xz1#

这有用吗?

poemText = poemText.trim().replaceAll("\n ", "\n")

因为句子之间有空格,所以首先trim()去掉字符串的开头和结尾,然后用 \n

flvtvl50

flvtvl502#

你可以用 ^\h+ 要匹配字符串开头的一个或多个水平空格字符,请使用 (?m) 启用多行。
在替换中使用空字符串。

val poemText = """
Blow the candles real hard,
 Coz now you have aged,
Don't pretend so much my dear,
 Don't behave so sage,
 Happy birthday to you,
 Have a nice day,
Make the most of your day!"""

    println(
        """(?m)^\h+"""
        .toRegex()
        .replace(poemText, "")
    )

输出

Blow the candles real hard,
Coz now you have aged,
Don't pretend so much my dear,
Don't behave so sage,
Happy birthday to you,
Have a nice day,
Make the most of your day!

查看kotlin演示

sbtkgmzw

sbtkgmzw3#

您可以这样使用replace with regex:

poemText = poemText.replace("""^\s*|\s*$""".toRegex(), "")
                   .replace("""\s*(\r|\n|\r\n)\s*""".toRegex(), "\n")

代码示例
第一个替换将删除文本开头和结尾的所有空格,第二个替换将删除每行结尾和开头的空格。

bmp9r5qi

bmp9r5qi4#

我想你可以把java变成kotlin

String text = "Blow the candles real hard,\n " +
            "    Coz now you have aged,\n " +
            "    Don't pretend so much my dear,\n " +
            "    Don't behave so sage,\n " +
            "    Happy birthday to you,\n " +
            "    Have a nice day,\n " +
            "    Make the most of your day!";

    String[] lines = null;
    lines = text.split("\n");

    String newText = "";
    for(int i = 0 ; i<lines.length ; i++){
        newText = (newText + lines[i]).trim()+"\n";
    }

    Log.e("newText",newText);

相关问题