This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Escape double quote in VB string
I am assigning variables below with string values, and I would like to print these with quotations, although I am not sure how to accomplish this. So far everything prints fine, except for without quotations. What I have is below:
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<<<
EDIT
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
I am indirectly populating str1 through str5, but I do not want to print all of the items with quotations, so how might I adjust the solution to accomplish this?
Try escaping your double quotes by typing the " twice. Also I find String.Format is tidier than concatenation, and if you wrap your StreamWriter in a using block, you don't need to dispose of it, as this is done by the garbage collector.
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
Also, you could probably give your variables clearer names. Naming them after the type is considered bad practice, as it doesn't really give us any information about what information the variable holds. Prefixing an Integer or a Single with str is worse, as somebody reading your code could wrongly think that the variable is a string, and thus try and treat it like such.
Edit: In response to your comment, first of all, in a VB.Net string, "" represents a single instance of a double quote, if you want to remove a double quote, just remove the "" and leave everything else intact. Secondly, it really doesn't matter if some of your strings are indirectly populated, you don't need to create a new variable to use them in a new string. In your code tu and str2 are pointing at the same piece of data, as are tu2 and str4, there is no need to create a new variable. If you have a piece of data held in a variable, you don't need to create a new variable to use it in a different way.
When your output is so regular (and possibly may contain many more strings) then an alternative that you may want to consider is this:
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
You still use the "" to indicate an inline quote, but you only need to do it twice. If your list of strings gets larger you only need to add them to the array (or it could be a list or any other enumerable).
Related
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)
I have into a string a replace, but I want to use it as a real vb.net function, There are a possibility to do this? For example:
dim str as string = "my task"
dim func as string = "Replace(str, " ", "-")"
dim result as string = 'here I must to use func string to have into result "my-task"
help me please
This is how to do it:
Dim inputString As String = "my task"
Dim methodName As String = "Replace"
Dim arguments = New String() {" ", "-"}
Dim result = CallByName(inputString, methodName, CallType.Method, arguments)
This is equivalent to:
Dim inputString As String = "my task"
Dim result = inputString.Replace(" ", "-")
Although it is worth noting: it is very likely that there are better ways to organize your code. Executing functions from a string have multiple downsides that you might want to avoid.
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)
I need to pass in parameters to my sub/function.
When the parameter is passed, the value in the string, I would like to get the value evaluated and sent as:
Dim strParams As String = drRow(0)
' drRow is a row from DB Table. the value in drRow(0) =
' "#FromDate=""" & Now.AddDays(-10).ToShortDateString & """&#ToDate=""" & Now.AddDays(-4).ToShortDateString "
I would like to see this converted to:
Dim strFinal as string
strFinal = ProcessString(strParams)
End Result should be:
strFinal = "#FromDate=10/09/2011&#ToDate=10/15/2011"
Any ideas how I can do this. I am getting the initial string from DB, I need to convert to the final string, I am not able to figure out how to write the "ProcessString" function.
Thanks for looking.
"IF" you can change your parameter statement to something simple like:
#FromDate=;-10;#ToDate=;-4
Then you can do something like this:
Dim strParams As String = "#FromDate=;-10;#ToDate=;-4"
Dim value As String = String.Empty
Dim parts() As String = strParams.Split(";"c)
If parts.Length = 4 Then
Dim fromDays As Integer
Dim toDays As Integer
If Integer.TryParse(parts(1), fromDays) AndAlso Integer.TryParse(parts(3), toDays) Then
value = parts(0) + Now.AddDays(fromDays).ToShortDateString + parts(2) + Now.AddDays(toDays).ToShortDateString
End If
End If
MessageBox.Show("Value = " & value)
If it's anything more complicated than that then you will have to start parsing every part of your string with lots of If and Select statements-- you should probably heed Jim Mischel's advice and try a different approach.
This is the end result of what i used based on suggestions.. Thanks Guys.
Public Function ProcessParameters(ByVal strParams As String) As String
Dim arrParams() As String
'strParams = "#FromDate=-10;&#ToDate=-4;&#CompanyID=1"
arrParams = strParams.Split(";")
Dim arrP() As String
Dim strFinalParams As String = ""
For Each strP As String In arrParams
arrP = strP.Split("=")
If arrP(0).ToString.EndsWith("Date") Then
strFinalParams &= arrP(0) & "=" & Now.AddDays(arrP(1)).ToShortDateString
Else
strFinalParams &= arrP(0) & "=" & arrP(1)
End If
Next
Return strFinalParams
End Function
}
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 :)