首页 > 解决方案 > 删除新行上的空格,但保留该行

问题描述

我希望从不包含文本的行中删除空格,但不删除该行。由于空格字符很难识别,我将用“#”(hastag 字符)替换空格字符以更容易地展示示例。字符串看起来像这样:

"This is
########a long string
with many lines
#######
and the above is empty
####this is empty
#############
#######hello"

我希望输出将删除仅包含空格字符的行上的空格。我仍在使用“#”(hastag 字符)来展示空间。最终输出应如下所示:

"This is
########a long string
with many lines

and the above is empty
####this is empty

#######hello"

如果没有将主题标签字符用作空格字符,则预期输出应如下所示:

"This is
        a long string
with many lines

and the above is empty
    this is empty

       hello"

因此,为了完全澄清,我希望删除不包含文本的行上的空格字符,但不删除该行。

标签: vb.net

解决方案


将您的示例与 octothorpes (# 的另一个名称)一起使用并用代码中的空格替换它们,我们可以使用该String.IsNullOrWhiteSpace函数检查这些行并将它们替换为空字符串:

Module Module1

    Sub Main()
        Dim s = "This is
########a long string
with many lines
#######
and the above is empty
####this is empty
#############
#######hello"
        s = s.Replace("#", " ")
        Dim t = String.Join(vbCrLf, s.Split({vbCrLf}, StringSplitOptions.None).
                            Select(Function(a) If(String.IsNullOrWhiteSpace(a), "", a)))

        Console.WriteLine(t)

        Console.ReadLine()

    End Sub

End Module

输出:

This is
        a long string
with many lines

and the above is empty
    this is empty

       hello

推荐阅读