缩进一个字符串四个空格(在字符串中添加制表符)
缩进一个字符串四个空格(在字符串中添加制表符)
我正在尝试给一个字符串添加缩进,即在字符串的每一行前面添加4个空格。我想要添加缩进的字符串被称为StringToIndent
。
Public Class ModifyPage Private Sub Button_Test_Click(sender As Object, e As RoutedEventArgs) Handles Button_Test.Click Dim StringToIndent As String = ("This is the first row This is the second row This is the third and final row in MyString") Dim MySecondString As String = "This is a string in one line." Dim BothStringsTogether = StringToIndent & Environment.NewLine & MySecondString Debug.Write(BothStringsTogether) End Sub End Class
当前输出结果为:
This is the first row This is the second row This is the third and final row in MyString This is a string in one line.
我希望最终的代码(已缩进)输出为:
This is the first row This is the second row This is the third and final row in MyString This is a string in one line.
如何通过代码实现这个目标?是否有一种格式选项可以让我添加缩进?最好不需要循环遍历字符串并为每一行添加四个空格的方法。
编辑:实现预期输出的一种方法是将换行符替换为换行符再加上缩进。然而,肯定有更优雅的方法吧?
代码:
Dim StringToIndent As String = ("This is the first row This is the second row This is the third and final row in MyString") Dim indentAmount = 4 Dim indent = New String(" "c, indentAmount) StringToIndent = indent & StringToIndent.Replace(Environment.NewLine, Environment.NewLine & indent) Debug.Write(StringToIndent)