Replace Double Double Quotes - vb.net

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

Related

Insert a string at specified indexof position using VB.NET

I'm trying to insert the string " " or a blank space in a specified index on a textbox like so:
textbox = heybrowhatsup
I want to insert an " " on the indexes 4, 8 and 14, to get "hey bro whats up", but my code just won't work.
My code:
Dim str As String = sum2.Text
Dim insStr As String = " "
Dim strRes As String = str.Insert(15, insStr)
Dim str As String = sum2.Text
Dim insStr As String = " "
Dim strRes As String = str.Insert(3, insStr)
strRes = strRes.Insert(7, insStr)
strRes = strRes.Insert(12, insStr)
You must use strRes.Insert for second or more.
Any string manipulation creates a new String object. What you're doing is working perfectly in that it is creating a new String with the specified substring inserted at the specified position. As is always the case, if you want that String displayed in your TextBox then you must assign that String to the Text property of that TextBox.
The Space function is useful for formatting output and clearing data in fixed-length strings.
You can use space function as below.
Dim str As String = "heybrowhatsup"
Dim strRes As String = str.Insert(3, Space(1)).Insert(7, Space(1)).Insert(13, Space(1))
Or
You can do the same with insert function.
Dim str As String = "heybrowhatsup"
Dim insStr As String = " "
Dim strRes As String = str.Insert(3, insStr).Insert(7, insStr).Insert(13, insStr)

Splitting a full name string to separate variables (first, middle and last) without using the split function

So I was given the task to bifurcate a string with a full name and then print out the first and last name separately. For instance, input: Steve Robertson, output: First name: Steve Last name: Robertson.
I succeeded, it was fairly easy. But I'm having having trouble in dividing a full name string to first, last and middle. Here's what I've done so far.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim temp1 As String = ""
Dim integer1 As Integer = 1
Console.WriteLine("Enter the string you want to bifurcate: ")
string1 = Console.ReadLine()
While integer1 <> 0
integer1 = InStr(string1, " ")
Console.WriteLine(string1)
string2 = Left(string1, integer1)
Console.WriteLine(string2)
string3 = Mid(string1, integer1 + 1)
Console.WriteLine(string3)
string4 = Mid(string1, integer1 + 1)
Console.WriteLine(string4)
string1 = string4
End While
Console.WriteLine("First name is: " & string2)
Console.WriteLine("Second name is: " & string3)
Console.WriteLine("Third name is: " & string4)
Console.ReadKey()
End Sub
Keep in mind that I'm only printing almost every single variable to see what their value is during the iteration. I can only use the len() function and whatever is already in the code.
EDIT:
So I fiddled around and finally got the thing, without the loop, but I was wondering if there was a cleaner/right way to do this without repeating the variables and also not needing to create any new ones either.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim integer1 As Integer
Console.WriteLine("Enter the string you want to split: ")
string1 = Console.ReadLine()
integer1 = InStr(string1, " ")
string2 = Left(string1, integer1)
string3 = Mid(string1, integer1 + 1)
integer1 = InStr(string3, " ")
string4 = Left(string3, integer1)
string3 = Mid(string3, integer1 + 1)
Console.WriteLine("The first name is: " & string2)
Console.WriteLine("The middle name is: " & string4)
Console.WriteLine("The last name is: " & string3)
Console.ReadKey()
End Sub
Here is one way to do it. Loop through the characters from the input of the user. Continue to do so concatenating them together and throw them into a List(Of String) that way the can be easily written out at the end... This account's for multiple spaces as well if there's more than one in between names. Also I put some comment's into the code so it can be easier to understand.
Note: This is only one way to do it... (there are other ways)
CODE TRIED AND TESTED
Dim nList As New List(Of String)
Dim uStr As String = String.Empty
Console.WriteLine("Enter the string you want to bifurcate: ")
uStr = Console.ReadLine()
If Not String.IsNullOrEmpty(uStr) Then 'Make sure something was entered...
Dim tStr As String = String.Empty
'Loop through user's input...
Do Until uStr = String.Empty
For Each c As Char In uStr
If Not Char.IsWhiteSpace(c) Then 'If it's a space we can add to the current string...
tStr &= c.ToString
Else
'We can assume its another section of the name...
Exit For
End If
Next
'If its a space, remove it from current string...
If String.IsNullOrEmpty(tStr) Then uStr = uStr.Remove(0, tStr.Length + 1) : Continue Do
'Add the string to the list, could be first name, middle or lastname?
If nList.Count = 0 Then
nList.Add("First Name: " & tStr)
ElseIf nList.Count = 1 Then
nList.Add("Middle Name: " & tStr)
ElseIf nList.Count = 2 Then
nList.Add("Last Name: " & tStr)
End If
'Now we can remove what we got from the users input...
uStr = uStr.Remove(0, tStr.Length)
tStr = String.Empty
Loop
End If
'Finally write out the values...
Console.WriteLine(String.Join(Environment.NewLine, nList.ToArray))
Console.ReadLine()
Screenshot Of Program
Maybe something like this
Dim fullName = "Juan Perez"
Dim name = fullName.Substring(0, fullName.IndexOf(" "))
Dim lastName = fullName.Substring(fullName.IndexOf(" ") + 1)
How to separate full name string
I would suggest that you design extension methods that will return First and Last Name
Module Module1
<Extension()>
Public Function returnFirst(ByVal fullName As String) As String
Return fullName.Substring(0, fullName.IndexOf(" "))
End Function
<Extension()>
Public Function returnLast(ByVal fullName As String) As String
Return fullName.Substring(fullName.IndexOf(" ") + 1)
End Function
End Module
'call it
'import module1
Dim Name as string = 'FirstName LastName'
MessageBox.Show(NAME.returnFirst)
MessageBox.Show(NAME.returnLast)

How to keep character " as a part of string

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

Substring and return list of comma separated characters

Domain\X_User|X_User,Domain\Y_User|Y_User,
I'm using a SSRS report and I'm receiving the above value, I want to write visual basic function in the report ( Custom code) to split the above string and return the following value:
X_User,Y_User
I tried to write this code inside a custom code of the report body:
Public Function SubString_Owner(X As String) As String
Dim OwnerArray() As String = Split(X, ",")
Dim Names As String
Dim i As Integer = 0
While i <= OwnerArray.Length - 1
Dim NamesArr As String() = Split(OwnerArray(0), "|")
Names = NamesArr(1) + ","
i += 1
End While
Return Names
End Function
The problem is when trying to split OwnerArray(i), it gives an error but when using a fixed value, like zero, it builds fine. Can anyone figure out why this is?
Here is a more generic solution that will work with any number of items:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s))
Dim usersWithoutDomains As IEnumerable(Of String) = domainsAndUsers.Select(Function(s) s.Remove(0, s.IndexOf("\") + 1))
Dim users As IEnumerable(Of String) = usersWithoutDomains.Select(Function(s) s.Remove(s.IndexOf("|")))
Dim result As String = users.Aggregate(Function(s, d) s & "," & d)
Or if you want it as a single-line function, here:
Function Foo(sourceString As String) As String
Return sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s)).Select(Function(s) s.Remove(0, s.IndexOf("\") + 1)).Select(Function(s) s.Remove(s.IndexOf("|"))).Aggregate(Function(s, d) s & "," & d)
End Function
EDIT:
You may have to add Imports System.Linq to the top. Not sure if SSRS can use LINQ or not. If not, then here is a similar solution without LINQ:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c)
Dim usersWithoutDomains As String = String.Empty
For Each domainUser As String In domainsAndUsers
usersWithoutDomains &= domainUser.Remove(0, domainUser.IndexOf("\") + 1) & ","
Next
Dim strTest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User"
MsgBox(strTest.Split("|")(0).Split("\")(1) & " " & strTest.Split("|")(1).Split("\")(1))
Here's a simple way that will work with variable data as long as the pattern you've shown is strongly followed:
Imports System.Linq
Dim strtest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
'This splits the string according to "|" and ",". Now any string without _
a "\" is the user and Join adds them together with `,` as a delimiter
Dim result As String = Join((From s In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Where Not s.Contains("\")
Select s).ToArray, ",")
Just in case LINQ is unavailable to you here's a different way to the same results without LINQ:
Dim result As String = ""
For Each s As String In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
If Not s.Contains("\") Then
result += s & ","
End If
Next
result = result.TrimEnd(",".ToCharArray)

Format for a multiple Replace Commands

Lets say i have this in a shell
"chdir * && whoami.exe >> $$$"
I have this replacecommand
Dim ReplaceCommand as String = sCommand.Replace("*", UserDirect)
I also would like the $$$ to be replaced with a user chosen filepath.
I can get the file path chosen but it never puts it into the shell.
I have tried
Dim ReplaceCommand1, ReplaceCommand2 as String = sCommand.Replace("*" & "$$$", UserDirect & filepath)
Shell("cmd.exe" & ReplaceCommand1 & ReplaceCommand2)
Dim ReplaceCommand as String = sCommand.Replace("*", UserDirect) & ("$$$", filepath)
Shell("cmd.exe" & ReplaceCommand)
also
Dim ReplaceCommand1 as String = sCommand.Replace("*", UserDirect)
Dim ReplaceCommand2 as String = sCommand.Replace("$$$", filepath)
Shell("cmd.exe" & ReplaceCommand1 & ReplaceCommand2)
EDIT:
get a path to short error when I use commas in shell instead of &
Dim ReplaceCommand1 as String = sCommand.Replace("*", UserDirect)
Dim ReplaceCommand2 as String = sCommand.Replace("$$$", filepath)
Shell("cmd.exe", ReplaceCommand1 , ReplaceCommand2)
You can chain the Replace's together:
Dim ReplaceCommand1 as String = sCommand.Replace("*", UserDirect).Replace("$$$", filepath)
Shell("cmd.exe" & ReplaceCommand1)
Part of your examples don't compile cause of the syntax errors.
You're not using Shell() like you're supposed to.
Public Function Shell(
PathName As String,
Optional Style As Microsoft.VisualBasic.AppWinStyle = MinimizedFocus,
Optional Wait As Boolean = False,
Optional Timeout As Integer = -1
) As Integer
From the examples you gave, it looks like you're just throwing stuff together. Stop and think for a minute :)