How to keep character " as a part of string - vb.net

I am new to VB
Dim myStr As String
myStr = "00101"
Dim Rat As String
Rat = "0"
I wish to build new string that will contain myStr but with character "
I mean that final string FinStr should look like this:
FinStr = "AT+COPS=1,2,"00102",0" //where 0 is RAT
So how to keep the character " ?
What is the best function to build string?
Can I do:
FinStr = "AT+COPS=1,2,\"" & myStr & "\"," & Rat
Thanks

There are also a set of Control Characters available:
Try
Dim myStr As String = ControlChars.Quote & "00101" & ControlChars.Quote
I find this much more readable than multiple quotes stacked together.
If I understand your expected result, I would think something like this is what you want:
Dim myStr As String
myStr = ControlChars.Quote & "00101" & ControlChars.Quote
Dim Rat As String
Rat = "0"
FinStr = "AT+COPS=1,2," & myStr & "," & Rat

There are two ways to put double quotes in your string. The first option is to double the amount of quotes:
Dim MyString As String = """Hello, I am a string!"""
Notice that there are three quotes in the beginning and end of the above string. This is because the very first and the very last one represents the beginning and end of a string.
In order to put a quote in the middle of the string you only have to type two quotes "". Example: "He stopped for a moment, and yelled: ""I like bananas!"" "
The second option is to use the Chr() function:
Dim MyString As String = Chr(34) & "Hello, I am a string!" & Chr(34)
Chr(34) represents the quotation mark character.
If you want to read more about the Chr() function: https://msdn.microsoft.com/en-us/library/613dxh46%28v=vs.90%29.aspx
And if you want to read more about putting quotation marks in your string: https://msdn.microsoft.com/en-us/library/267k4fw5%28v=vs.90%29.aspx

Related

Substring a stringRaw from String1 to String2

If you didn't really get it what I actually want let me explain you better:
I have a:
stringRaw = "<img src=\"http://www.b92.net/news/pics/2015/01/15/111348233854b817af5b4bc991063053_v4 big.jpg\" title=\"\" alt=\"\" />"
Now I have to do some kind of substring from string1 = "<img src=\"" to string2 = "\" title=\"\" alt=\"\" />" and have to take what is in the middle of that which will be stringFinal = "http://www.b92.net/news/pics/2015/01/15/111348233854b817af5b4bc991063053_v4 big.jpg" in this case.
I can't use substring method since I never know how many characters can be in string1 and string2 also, seems like split method do not work as it should from THIS question on StackOverFlow.
edit For some reason my stringRaw has this value: vbCrLf & vbTab & vbTab & vbTab & "<img src=""http://www.b92.net/news/pics/2015/02/05/203819435354d39f17d74f0173575440_v4 big.jpg"" title="""" alt="""" />" & vbTab & vbTab
Anyway, I do what others advised and still I get an error that Index is out of range
Thank you for the answers in advance.
I was having issues going after the same characters so I went after text within the string such as "http" and "title=". Here it is in VB:
Dim startIndex As Int32 = stringRaw.IndexOf("http")
Dim endIndex As Int32 = stringRaw.IndexOf("title=") - 2
Return stringRaw.Substring(startIndex, endIndex - startIndex)
I used "http" and didn't include "://" just in case you need to get an "https" at some point. I used "title=" instead of "title" in case the word title ever showed up in the link.
I believe this code should grab the 'stringFinal' you desire.
// Get the index of 'src="'
Int32 startIndex = stringRaw.IndexOf("src=\"");
// Get the substring starting at 'src="' and ending at the first '"' after 'src="'.
stringRaw.Substring(startIndex, stringRaw.IndexOf("\"", startIndex) - startIndex);
Oh, sorry just noticed the VB tag. This is C# so the sytnax might be slightly different, but the functions and parameters should still be the same.
I forgot the - startIndex I was thinking that SubString second parameter was an index instead of count. Try adding that adjustment.
You could also use a regular expression. Something like:
Dim stringRaw as String = vbCrLf & vbTab & vbTab & vbTab & "<img src=""http://www.b92.net/news/pics/2015/02/05/203819435354d39f17d74f0173575440_v4 big.jpg"" title="""" alt="""" />" & vbTab & vbTab
Dim regx as New Regex("src=\""(.*)\""\s+title")
Dim match as Match = regx.Match(stringRaw)
If match.Success
' Outputs http://www.b92.net/news/pics/2015/02/05/203819435354d39f17d74f0173575440_v4 big.jpg
Console.WriteLine(match.Groups(1).Value)
End If
Public Function ExtractSrcAttribute(ByVal element As String) As String
Dim startToken As String = "src="""
Dim endToken As String = """"
Dim startIndex As Integer = element.IndexOf(startToken) + startToken.Length
Dim endIndex As Integer = element.IndexOf(endToken, startIndex)
If startIndex > element.Length OrElse endIndex > element.Length OrElse endIndex < startIndex Then
'error
End If
Return element.SubString(startIndex, endIndex)
End Function
As mentioned in my comment about you could use Regex to accomplish this easily. This uses a Positive-LookBehind and Positive-LookAhead. Please see below for example. This is tried and tested as well.
Dim rgex As New Regex("((?<=src=\\"").*)(?=\\""\s+title=)")
Dim mtch As Match = rgex.Match(TextBox1.Text)
If mtch.Success Then
MessageBox.Show(mtch.Groups(1).Value)
End If

VB.net string join, adds unneeded space

Having some issues in vb.net string to join two strings together for output to a txt document. My text document is getting an extra space between the two strings I join. This should not be happening.
If System.IO.File.Exists(path) = True Then
' Create a file to write to.
Dim sw As StreamWriter = System.IO.File.CreateText(path)
sw.WriteLine("Attribute VB_Name = " & Chr(34) & "KbTest" & Chr(34))
sw.WriteLine("")
sw.WriteLine("Public Sub DoKbTest()")
sw.WriteLine("'code here")
sw.WriteLine("Dim catia")
sw.WriteLine("set catia = GetObject(, " & Chr(34) & "CATIA.Application" & Chr(34) & ")")
sw.WriteLine("Dim partDocument1")
sw.WriteLine("Set partDocument1 = catia.ActiveDocument")
sw.WriteLine("Dim part1")
sw.WriteLine("Set part1 = partDocument1.Part")
sw.WriteLine("Dim hybridShapeFactory1")
sw.WriteLine("Set hybridShapeFactory1 = part1.HybridShapeFactory")
sw.WriteLine("Dim hybridShapeDirection1")
sw.WriteLine("Set hybridShapeDirection1 = hybridShapeFactory1.AddNewDirectionByCoord(1#, 2#, 3#)")
sw.WriteLine("Dim hybridBodies1")
sw.WriteLine("Set hybridBodies1 = part1.HybridBodies")
sw.WriteLine("Dim hybridBody1")
sw.WriteLine("Set hybridBody1 = hybridBodies1.Item(" & Chr(34) & "PointSetx" & Chr(34) & ")")
sw.WriteLine("dim skteches1")
sw.WriteLine("Set sketches1 = hybridBody1.HybridSketches")
sw.WriteLine("Dim sketch1")
sw.WriteLine("Set sketch1 = sketches1.Item(" & Chr(34) & "Sketch.1" & Chr(34) & ")")
sw.WriteLine("Dim reference1")
sw.WriteLine("Set reference1 = part1.CreateReferenceFromObject(sketch1)")
sw.WriteLine("Dim hybridShapeExtremum1")
sw.WriteLine("Set hybridShapeExtremum1 = hybridShapeFactory1.AddNewExtremum(reference1, hybridShapeDirection1, 1)")
sw.WriteLine("hybridBody1.AppendHybridShape hybridShapeExtremum1")
sw.WriteLine("Dim reference2")
Dim lessOneCount As String
Dim spacing As Double = 0
Dim count As String
Dim setString As String
'loop
THIS IS THE PART OF THE CODE THAT IS ADDING EXTRA SPACES
For i = 1 To numbOfPoints Step 1
count = Str(i)
count.Replace(" ", "")
MsgBox(count)
If i < 2 Then
lessOneCount = "hybridShapeExtremum1"
Else
lessOneCount = "HybridShapePointOnCurve" + Str(i - 1)
End If
sw.WriteLine("reference2 = part1.CreateReferenceFromObject(" + lessOneCount + ")")
setString = "Dim hybridShapePointOnCurve" + count
sw.WriteLine(setString)
setString = "hybridShapePointOnCurve" + count + " = hybridShapeFactory1.AddNewPointOnCurveWithReferenceFromDistance(reference1, reference2, spacing, False)"
sw.WriteLine(setString)
setString = "hybridShapePointOnCurve" + count + ".DistanceType = 1"
sw.WriteLine(setString)
setString = "hybridBody1.AppendHybridShape(hybridShapePointOnCurve" + count + ")"
sw.WriteLine(setString)
Next
sw.WriteLine("End Sub")
sw.Flush()
sw.Close()
End If
Sample output:
Dim hybridShapePointOnCurve 2
SHOULD be:
Dim hybridShapePointOnCurve2
What modifications should I make to the way I join strings?
Thanks!
Realized my comment didn't answer your question completely, so a few things:
The String.Replace method doesn't work like you think it does. Saying count.Replace(" ", "") doesn't actually change the variable count; the function actually returns a new string. For it work like you want, you would need to do count = count.Replace(" ", "").
Consider using a StringBuilder instead of concatenating a bunch of strings together. It will greatly improve performance. When using the StringBuilder class, you also wouldn't need to write to the StreamWriter until the very end, simply by calling sw.Write(stringBuilderObject.ToString())
I haven't used VB.NET in a while, but I would check what Str(i) returns. Instead of using VB functions, consider using .NET functions by saying count = i.ToString(). According to Sky, the Str function indeed returns a space because it reserves it for the negative sign. Based on this, I would use the .ToString() method instead.
I spoke to quickly in my comment, the Str function reserves room for the sign, since it is a positive number there is no sign, if it was negative there would be a minus sign there. Try Trim(Str(i)) instead
From above link(emphasis mine):
This example uses the Str function to return a String representation of a number. When a positive number is converted to a string, a leading space is always reserved for its sign.

How can i replace " in vb.net

How can i replace this string:
<say"Hello">
with another strings in VB.net?
this program is not working!!
Text1.Text = Text1.Text.Replace("<say"Hello">", " ")
To get a literal quote in a string, use a double quote ("") as so:
Text1.Text = Text1.Text.Replace("<say""Hello"">", " ")
The string will then be interpreted as this:
<say"Hello">

How to insert " character in string variable?

How to insert this?
Dim SpCharacter As String = " " "
or
Dim XMLSitemap As String = "<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">"
insert with all Content " and > and etc
You need to escape it by doubling it:
Dim SpCharacter As String = " "" "
Dim XMLSitemap As String = "<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"">"
See String Basics in Visual Basic on MSDN:
Visual Basic interprets two quotation marks in a string literal as one quotation mark in the string.
In VB.NET you can escape " by passing it twice in a row:
Dim SpCharacter As String = " "" "
or
Dim XMLSitemap As String = "<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"">"

Replace Double Double Quotes

I need to replace double double quotes but not replace fields with empty values.
Question: How can I replace double double quotes and not replace empty columns?
Original Line
""COTTAGE"","PENNINGTON, NJ","","123456789"
Expected outcome
"COTTAGE","PENNINGTON, NJ","","123456789"
I have created a class that will do the trick, but it replaces all double double quotes, including the empty field:
My code outcome
"COTTAGE","PENNINGTON, NJ",","123456789"
as you can see my code fixes COTTAGE, but kills the empty column after ,NJ to have a single double quote.
Public Class FixFileErrors
Public Shared Sub RemoveDoubleDoubleQuotes(ByVal FilePathandName As String)
Dim OriginalFile, RevisedFile, LineofText As String
OriginalFile = FilePathandName
RevisedFile = Replace(OriginalFile, ".txt", "revised.txt")
Dim srFileReader As System.IO.StreamReader
srFileReader = System.IO.File.OpenText(OriginalFile)
'Dim srFileWritter As System.IO.StreamWriter
Dim srFileWritter As New System.IO.StreamWriter(RevisedFile)
Do Until srFileReader.EndOfStream
LineofText = srFileReader.ReadLine
LineofText = ReplaceDoubleDoubleQuotes(LineofText)
srFileWritter.WriteLine(LineofText)
LineofText = Nothing
Loop
End Sub
Public Shared Function ReplaceDoubleDoubleQuotes(ByVal Line As String) As String
Dim NewLine As String
Dim strFindText As String = Chr(34) & Chr(34)
Dim strReplaceText As String = Chr(34)
NewLine = Replace(Line, strFindText, strReplaceText)
Return NewLine
End Function
End Class
Public Shared Function ReplaceDoubleDoubleQuotes(ByVal Line As String) As String
Dim NewLine As String
Dim doubleDoubleQuotes As String = Chr(34) & Chr(34)
Dim doubleQuote As String = Chr(34)
'Your original replacement
NewLine = Replace(Line, doubleDoubleQuotes, doubleQuote)
'Replacement to fix double-quotes between commas
NewLine = Replace(NewLine, "," & doubleQuote & ",", "," & doubleDoubleQuotes & ",")
Return NewLine
End Function