如何在VB.NET中打印带引号的字符串

时间:2012-09-30 17:27:00

标签: vb.net string

  

可能重复:
  Escape double quote in VB string

我在下面用字符串值分配变量,我想用引号打印这些变量,虽然我不知道如何实现这一点。到目前为止,一切都打印得很好,除了没有引用。我的内容如下:

    Dim tU As String = "Print_Me"
    Dim tU2 As String = ""
    Dim str1 As Integer = 1
    Dim str2 As String = tU
    Dim str3 As Single = 3.5
    Dim str4 As String = tU2

    Dim fw As New System.IO.StreamWriter("testfile.txt")
    fw.WriteLine(str1 & "," & str2 & "," & str3 & "," & str4 & "," & 0)

    fw.Close()
    fw.Dispose()
    'prints>>>1,Print_Me,3.5,,0<<<
    'I like to print>>>1,"Print_Me",3.5,"",0<<<

修改

    Dim tU As String = "Print_Me"
    Dim tU2 As String = ""
    Dim str1 As Integer = 1
    Dim str2 As String = tU
    Dim str3 As Single = 3.5
    Dim str4 As String = tU2
    Dim str5 As Integer = 0

    Using fw As New System.IO.StreamWriter("testfile.txt")
        fw.WriteLine(String.Format("""{0}"",""{1}"",""{2}"",""{3}"",""0""", str1, str2, str3, str4, str5))
    End Using

    ''Currently prints>>> "1","Print_Me","3.5","","0"

    ''I would like to print>>> 1,"Print_Me",3.5,"",0

我通过str5间接填充str1,但我不想打印带引号的所有项目,那么我如何调整解决方案来实现这一目标呢?

2 个答案:

答案 0 :(得分:2)

尝试两次输入"来转义双引号。另外我发现String.Format比串联更整洁,如果你将StreamWriter包装在一个使用块中,你就不需要处理它,因为这是由垃圾收集器完成的。

Dim str1 As Integer = 1
Dim str2 As String = "Print_Me"
Dim str3 As Single = 3.5
Dim str4 As String = ""

Using fw As New System.IO.StreamWriter("testfile.txt")
    fw.WriteLine(String.Format("""{0}"",""{1}"",""{2}"",""{3}"",""0""", str1, str2, str3, str4))
End Using

另外,你可以给你的变量更清晰的名字。在类型之后命名它们被认为是不好的做法,因为它实际上并没有给我们任何关于变量保存的信息的信息。使用str对整数或单个字符进行前缀更糟糕,因为读取代码的人可能错误地认为变量是字符串,因此请尝试对待它。

编辑:在回复你的评论时,首先,在VB.Net字符串中,""表示双引号的单个实例,如果要删除双引号,只需删除{{ 1}}并保持其他一切完好无损。其次,如果你的某些字符串是间接填充的,那么你不需要创建一个新变量来在新字符串中使用它们。在您的代码中,""tu指向的是同一条数据,str2tu2也是如此,因此无需创建新变量。如果您在变量中保存了一段数据,则无需创建新变量即可以其他方式使用它。

答案 1 :(得分:0)

当您的输出如此规则(并且可能包含更多字符串)时,您可能需要考虑的另一种选择是:

Dim str1 As Integer = 1
Dim str2 As String = "Print_Me"
Dim str3 As Single = 3.5
Dim str4 As String = ""

Dim strings() As String = _
{ _
    str1, _
    str2, _
    str3, _
    str4, _
    "0" _
}

Using fw As New System.IO.StreamWriter("testfile.txt")
    fw.WriteLine( _
        String.Join( _
            ",", _
            strings.Select(Function (s) """" & s & """")))
End Using

您仍然使用""来表示内联引用,但您只需要执行两次。如果您的字符串列表变大,您只需要将它们添加到数组中(或者它可以是列表或任何其他可枚举的字符串。)