Daniel May
Daniel May

Reputation: 21

How do add one double quotation mark (") into a string in VB.NET?

Currently I have

codeString &= "matrixDictionary(" & Chr(34) & UCase(Mid(currentPhrase, currentPhrase.Count, 1)) & Chr(34) & " )"

To codeString I want this to add

matrixdictionary("A")

However, currently, it's adding

matrixdictionary(""A"")

How do I add a " to a string on it's own? I've tried looking it up, but every other method suggested doesn't see to work, or isn't relevant.

Upvotes: 2

Views: 5197

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

There is no problem to solve here. A literal double-quote is simply represented by two double-quotes, with the first escaping the second in order to distinguish it from a delimiter. These all produce equal String objects:

Dim str1 = "He said " & Chr(34) & "Hello" & Chr(34) & " to me."
Dim str2 = "He said " & ControlChars.Quote & "Hello" & ControlChars.Quote & " to me."
Dim str3 = "He said ""Hello"" to me."

The first one - the one you're using - is the worst option because it is not self-documenting like the second or succinct and easy to read like the third. Output any of those three values, e.g. to the console or a Label, and you will see this:

He said "Hello" to me.

In your specific case, you should be using literal double-quotes and string interpolation:

codeString &= $"matrixDictionary(""{Mid(currentPhrase, currentPhrase.Count, 1).ToUpper()}"" )"

I've also replaced UCase, which is a VB6 holdover, with ToUpper. I'd suggest doing the same for Mid with Substring. Finally, I've left it in but I suspect that you have an erroneous space in your String too, before the closing parenthesis.

Upvotes: 2

Related Questions