I have a function in SSRS using VB.NET as follows:
Public Function GenerateCSV(byval str as string, byval str1 as string, byval str2 as string, byval GrpName as string)
IF GroupName <> GrpName THEN
GroupName = GrpName
CSVString = ""
END IF
IF str = ""
CSVString = ""
ELSE
CSVString = CSVString & str & ", " & str1 & ", " & str2 & ", "
END IF
return CSVString
End function
This works great is str, str1 and str2 have a value and only one value. But I want to make it so if the value isn't there or there is only one value there is no comma and if there are multiple commas there is a comma. Is there an easy way to do this?
Thanks!
Create array from your non-empty arguments.
Use String.Join method to concatenate array elements.
Example:
String.Join("," values)
http://msdn.microsoft.com/en-us/library/system.string.join
Related
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)
I send an arrey with the length of 26 twice to a function like this:
....
SaveXML strXmlItem, DFCCM, SCTM, Zieltabelle
SaveXML strXmlItem, DFCCS, SCTS, Zieltabelle
....
After the first invokation:
SaveXML strXmlItem, DFCCM, SCTM, Zieltabelle
Content of strXmlItem are changed. This array with other variablesis definedlike this:
Dim strSql, strXmlItem(), strA2l, strHex As String
and the function is:
Private Function SaveXML(strarr(), DFCC As String, SCT As String, ByVal Zieltabelle As String)
strarr(4) = DFCC
strarr(6) = SCT
For K = 0 To UBound(strarr)
MsgBox strarr(K)
Next K
'XML-Syntax anpassen
For J = 1 To conAnzahlFelder - 1
strarr(J) = MakeQuotes(strarr(J)) & ", "
Next J
strarr(conAnzahlFelder) = MakeQuotes(strarr(conAnzahlFelder)) & ")"
' Anfügeabfrage zusammenbasteln
strSql = "Insert Into " & Zieltabelle & " ("
For J = 1 To conAnzahlFelder
strSql = strSql & "f" & Trim(CStr(J - 1)) & ", "
Next J
strSql = strSql & "f" & Trim(CStr(conAnzahlFelder)) & ") "
strSql = strSql & "Values ("
For J = 1 To conAnzahlFelder + 1
strSql = strSql & strarr(J - 1)
Next J
MsgBox strSql
DoCmd.RunSQL strSql
End Function
How can I solve the problem?
there are a lot of issues in your code. But to answer your question
first:
try:
Private Function SaveXML(ByVal strarr(), DFCC As String, SCT As String, ByVal Zieltabelle As String)
instead of
Private Function SaveXML(strarr(), DFCC As String, SCT As String, ByVal Zieltabelle As String)
Google for the difference between ByVal and ByRef.
Second:
you really should use Option Explicit on the beginning of each module. You use a lot of undeclared variables. This can cause additional issues.
Third:
Dim strSql, strXmlItem(), strA2l, strHex As String
generates only ONE string variable (strHex). The others are declared as Variant if you use that Syntax. This works in some other languages but not in VBA!
and last but not least:
you declare a Function but you do not return any value for it. Either you do not want to return something (then you shouldn't declare it as Function) or you should provide a return value.
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).
I've got a ProperCase function in my .Net code like so
Public Function ProperCase(ByVal strValue As String) As String
Dim outString As String = ""
Dim badWords As String = "and, at, do, de, du, USA, UK"
Dim splitter(1) As Char
splitter(0) = " "
Dim splitString As String() = strValue.Split(splitter)
For Each s As String In splitString
If badWords.Contains(s) Then
outString = outString & s & " "
Else
outString = outString & StrConv(s, VbStrConv.ProperCase) & " "
End If
Next
Return Trim(outString)
End Function
I need to propercase double barrelled names like Taylor-Smith but it's coming out like Taylor-smith because the splitter is a space so I modified the code like so.
Public Function ProperCase(ByVal strValue As String) As String
Dim outString As String = ""
Dim badWords As String = "and, at, do, de, du, USA, UK"
Dim splitter(2) As Char
splitter(0) = " "
splitter(1) = "-"
Dim splitString As String() = strValue.Split(splitter)
For Each s As String In splitString
If badWords.Contains(s) Then
outString = outString & s
Else
outString = outString & StrConv(s, VbStrConv.ProperCase)
End If
Next
Return Trim(outString)
End Function
So I added an extra splitter into the function but now it's not returning the value with the hyphen in. I removed the & " " from the end of the outString but i'm not sure what I can replace it with.
I've tried to add & splitter but it always returns a hyphen even if the splitter was a space.
Currently I'm getting this with my modified code
Mr TomHart
Mr JamieTaylorSmith
And With the first version of the code I got this
Mr Tom Hart
Mr Jamie Taylor-smith
My expected outputs are like so...
Mr Tom Hart
Mr Jamie Taylor-Smith
Any ideas?
I wouldn't alter the split method at all to catch the hyphens. Instead I would look at the outstring. Resulting from your first method before you changed it. Probably in the If inside the loop.
This is a really quick idea to base it on... not necessarily the cleanest version of it but should give you the idea:
Dim outstring As String = "Michael James-smith"
Dim indexOfCharToCheck As Integer = outstring.LastIndexOf("-"c) + 1
Dim finalString As String = outstring.Substring(0, indexOfCharToCheck) & UCase(outstring(indexOfCharToCheck).ToString) & outstring.Substring(indexOfCharToCheck + 1)
MsgBox(finalString)
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
}