I want to conditionally append a string, derived from a function, to a string builder. The required condition is that the function is not returning a blank string ("").
The purpose of conditionally appending the string is to avoid AppendLine() appending a line when the string (returned from the function) being appended is empty.
My current code (wrapping the function in a condition calling the very same function):
Dim builder As New System.Text.StringBuilder()
builder.Append("Some text...").AppendLine()
If Not IsNothing(someFunction(someParameterAA, someParameterAB)) Then
builder.Append(someFunction(someParameterAA, someParameterAB)).AppendLine()
End If
If Not IsNothing(someFunction(someParameterBA, someParameterBB)) Then
builder.Append(someFunction(someParameterBA, someParameterBB)).AppendLine()
End If
builder.AppendLine().Append("...some text.")
Dim s As String = builder.ToString
MessageBox.Show(s)
It is my hope that a more efficient alternative exists (efficient in terms of the amount of code to be written). Ultimately, I'd like to avoid calling the same function twice however I cannot independently add the builder.Append line of code to my function. Is it instead possible to target builder.Append?
Example of the potential logic:
If `builder.Append()` inside the following brackets is not an empty string then:
(
builder.Append(someFunction(someParameterAA, someParameterAB)).AppendLine()
)
If anyone has a solution on the above, bear in mind the prequisite of concision (=< 2) lines of code additional to the builder.Append() line.
I'm open to any other suggestions.
Create another method to do the appending like so:
CheckBeforeAppend(someFunction(someParameterAA, someParameterAB), builder)
CheckBeforeAppend(someFunction(someParameterBA, someParameterBB), builder)
....
Public Sub CheckBeforeAppend(s As String, sb As StringBuilder)
If Not String.IsNullOrEmpty(s)
sb.Append(s).AppendLine()
End If
End Sub
A simple refactor such as this shortens your original code and means you don't need to duplicate the null or empty check on the return value of your function.
And for the extension method (place this code in a Module):
<Extension()>
Public Sub CheckBeforeAppend(s As String, sb As StringBuilder)
If Not String.IsNullOrEmpty(s)
sb.Append(s).AppendLine()
End If
End Sub
usage:
someFunction(someParameterAA, someParameterAB).CheckBeforeAppend(sb)
or for an extension on StringBuilder:
<Extension()>
Public Sub CheckBeforeAppend(sb As StringBuilder, s As String)
If Not String.IsNullOrEmpty(s)
sb.Append(s).AppendLine()
End If
End Sub
usage:
builder.CheckBeforeAppend(someFunction(someParameterAA, someParameterAB))
You can avoid calling the function twice by storing the result of the function in a variable.
Dim myString As String = someFunction(someParameterAA, someParameterAB)
If myString <> "" Then
builder.Append(myString).AppendLine()
End If
myString = someFunction(someParameterBA, someParameterBB)
If myString <> "" Then
builder.Append(myString).AppendLine()
End If
This way you just call the function once and check your conditions with the variable. Also the code looks a lot smaller and more understandable.
Related
In my class today I was told change some of my sub-procedures to functions, and when I asked why it's better my teacher struggled to answer, generally, i've always thought that functions should only really be used when a value is returned. In the two examples below; is there one method that should be used over the other, or does it not matter? And if it does matter why?
Thanks in advance.
Method 1 (Sub-Proc):
Sub EncryptString(ByVal unkString, ByRef encryptedString)
For i = 1 To Len(unkString)
encryptedString += "*"
Next
End Sub
Method 2 (Function):
[In main I assign the variable "encryptedString" to this function].
Function encryptString(ByVal unkString) As String
For i = 1 To Len(unkString)
encryptString += "*"
Next
End Function
You've misunderstood what they're trying to tell you. In your Function example there is no difference. What your teacher is expecting is like this:
Function EncryptString(ByVal unkString) As String
Dim encryptedString As String = ""
For i = 1 To Len(unkString)
encryptedString += "*"
Next
Return encryptedString
End Function
This is a cleaner and more reusable way than modifying a field, an argument passed ByRef, or the underlying variable of the function
Your example show one of the multiple reason, who initialize the data is unclear. With your sample code, the first option would append to the passed string while the second would create a new string.
The first method would have to specify if it needs an empty string or explain why it appends. While the second method clearly show that a new string will be returned.
Sub Main()
Dim u, e As String
u = "123"
e = "123"
EncryptString1(u, e)
Console.WriteLine(e) ' Display: 123***
u = "123"
e = "123"
e = encryptString2(u)
Console.WriteLine(e) ' Display: ***
Console.ReadLine()
End Sub
Sub EncryptString1(ByVal unkString As String, ByRef encryptedString As String)
For i As Integer = 1 To Len(unkString)
encryptedString += "*"
Next
End Sub
Function encryptString2(ByVal unkString As String) As String
encryptString2 = ""
For i As Integer = 1 To Len(unkString)
encryptString2 += "*"
Next
End Function
Please have option strict on. Also, personally, I rather create a variable instead of using the function name, use .Length instead of Len() and concatenate with & instead of +.
Function encryptString3(ByVal unkString As String) As String
Dim encryptedString As String = ""
For i As Integer = 1 To unkString.Length
encryptedString &= "*"
Next
Return encryptedString
End Function
Or just use the New operator of the String class.
Dim encryptedString as New String("*"c, unkString.Length)
Well, when I was learning this stuff, it was always to use functions to calculate values and subs to do other stuff. I guess for something very general, it doesn't really matter which methodology you use, as you have illustrated in your example. See the link below for further discussion on this topic.
http://analystcave.com/vba-function-vs-vba-sub-procedures/
I am familiar with this post: How to Return a result from a VBA Function but changing my code does not seem to help.
I want to write a simple function in VBA that allows to lowercase an input sentence. I wrote this:
Private Function Converter(inputText As String) As String
Converter = LCase(inputText)
End Function
Sub test()
Dim new_output As String
new_output = Converter("Henk")
MsgBox (new_output)
End Sub
I tried following the advice I found at another stackoverflow post. I made me change this:
Private Function Converter(inputText As String)
Set outputText = LCase(inputText)
End Function
Sub test()
Dim new_output As String
Set new_output = Converter("Henk")
MsgBox (new_output)
End Sub
However, now I get an error that an object is required. Why does it require an object now? I dont get it...
Set outputText = LCase(inputText)
The Set keyword is reserved for Object data types. Unlike VB.NET, String in VBA is a basic data types.
So you dont Set a variable to a string. Drop the second version of your code altogether. It doesn't make sense. That "advice" was probably in another context.
To fix your first version
1- Assign the returned result to the name of the function Converter
2- It would be beneficial to specify explicitly the return type, as String. Currently it is a Variant that always embeds a String, so better make it explicit:
' vvvvvvvvv
Private Function Converter(inputText As String) As String
Converter = LCase(inputText) ' <------------ assign return to name of function
End Function
I have to create a class in Visual Basic called StringWork.
Public Class StringWork
Now i wrote a shared function in the class called Working that can take a string or a string and Boolean.
Public Shared Function Working(ByVal SingleString as string, optional BValu as Boolean = true)as string
if(working(SingleString))then
'The handling of the string
else if (working(SingleValue, BValue) then
'do something else with string
end if
end function
The function I wrote is returning a string.
Can I access the string passed and edit characters in the string or change the position of characters?
You use that optional parameter to determine how you handle that string:
Public Shared Function Working(ByVal singleString as string, _
Optional bValue as Boolean = True) As String
If bValue Then
'Handle the true part manipulating the result string
Else
'Handle the false part manipulating the result string
End If
End Function
If you call this function like this:
Dim test As String = StringWork.Working("I am Spartacus")
it will call that Working function with bValue = true.
What bValue is suppose to represent isn't very clear from the code nor the post.
In VB.NET, and other .NET languages, strings are immutable. Typically, if you need to modify a string that is passed to your method, you would return the modified string. If however, you need it to modify the parameter, you can specify that it is a "ByRef" argument, in which case you will be able to set it to point to a new string object which will affect the variable that was passed into the method as a parameter. If you need a truly mutable string, you will need a character array or a StringBuilder object.
I'm having some trouble compiling some VB code I wrote to split a string based on a set of predefined delimeters (comma, semicolon, colon, etc). I have successfully written some code that can be loaded inside a custom VB component (I place this code inside a VB.NET component in a plug-in called Grasshopper) and everything works fine. For instance, let's say my incoming string is "123,456". When I feed this string into the VB code I wrote, I get a new list where the first value is "123" and the second value is "456".
However, I have been trying to compile this code into it's own class so I can load it inside Grasshopper separately from the standard VB component. When I try to compile this code, it isn't separating the string into a new list with two values. Instead, I get a message that says "System.String []". Do you guys see anything wrong in my compile code? You can find an screenshot image of my problem at the following link: click to see image
This is the VB code for the compiled class:
Public Class SplitString
Inherits GH_Component
Public Sub New()
MyBase.New("Split String", "Split", "Splits a string based on delimeters", "FireFly", "Serial")
End Sub
Public Overrides ReadOnly Property ComponentGuid() As System.Guid
Get
Return New Guid("3205caae-03a8-409d-8778-6b0f8971df52")
End Get
End Property
Protected Overrides ReadOnly Property Internal_Icon_24x24() As System.Drawing.Bitmap
Get
Return My.Resources.icon_splitstring
End Get
End Property
Protected Overrides Sub RegisterInputParams(ByVal pManager As Grasshopper.Kernel.GH_Component.GH_InputParamManager)
pManager.Register_StringParam("String", "S", "Incoming string separated by a delimeter like a comma, semi-colon, colon, or forward slash", False)
End Sub
Protected Overrides Sub RegisterOutputParams(ByVal pManager As Grasshopper.Kernel.GH_Component.GH_OutputParamManager)
pManager.Register_StringParam("Tokenized Output", "O", "Tokenized Output")
End Sub
Protected Overrides Sub SolveInstance(ByVal DA As Grasshopper.Kernel.IGH_DataAccess)
Dim myString As String
DA.GetData(0, myString)
myString = myString.Replace(",", "|")
myString = myString.Replace(":", "|")
myString = myString.Replace(";", "|")
myString = myString.Replace("/", "|")
myString = myString.Replace(")(", "|")
myString = myString.Replace("(", String.Empty)
myString = myString.Replace(")", String.Empty)
Dim parts As String() = myString.Split("|"c)
DA.SetData(0, parts)
End Sub
End Class
This is the custom VB code I created inside Grasshopper:
Private Sub RunScript(ByVal myString As String, ByRef A As Object)
myString = myString.Replace(",", "|")
myString = myString.Replace(":", "|")
myString = myString.Replace(";", "|")
myString = myString.Replace("/", "|")
myString = myString.Replace(")(", "|")
myString = myString.Replace("(", String.Empty)
myString = myString.Replace(")", String.Empty)
Dim parts As String() = myString.Split("|"c)
A = parts
End Sub
'
'
End Class
Well, knowing nothing about Grasshopper, I'm just going to have to guess...
System.String [] is what .NET would print if you called ToString() on a string array. So, I'm gonna guess that you've given Grasshopper an array where it wants a single string.
So, with a little further guessing, how 'bout we try:
Dim parts As String() = myString.Split("|"c)
For I = 0 to parts.Length -1
DA.SetData(I, parts[I])
Well, I tried the code snippet you suggested... but it didn't quite work. I think the problem in the original code is that I'm trying to send a list of values (ie. parts) to a single output node. So, when I use DA.SetData(0,parts) I'm writing a list of values to the first output node of my compiled component. However, I think the problem is that the component doesn't know that parts is a list. In the example I gave before, if my incoming string is "123,456" then my result split list should have two values (123 and 456). I don't think I have declared parts to be a list. Do you have any ideas on how to do this? Again, if you click on the link in the original email (while using Internet Explorer... I'm not sure why Firefox isn't opening it) you should see a screenshot of the setup in the Grasshopper plugin which should help give you an idea of what's going on. Thanks again for your help.
I have an HTMLElementCollection that I'm going through using a For Each Loop to see if the InnerHTML contains certain words. If they do contain any of those keywords it gets saved into a file.
Everything works fine but I was wondering if there is a way to simplify. Here's a sample
For Each Helement As HtmlElement In elements
If Helement.InnerHtml.Contains("keyword1") Or Helement.InnerHtml.Contains("keyword2") Or Helement.InnerHtml.Contains("keyword3") Or Helement.InnerHtml.Contains("keyword4") Or Helement.InnerHtml.Contains("keyword5") = True Then
' THE CODE TO COPY TO FILE
End If
Next Helement
Does anything exist that would work like:
If Helement.InnerHtml.Contains("keyword1", "keyword2", "keyword3", "keyword4", "keyword5")
The way I'm doing it now just seems wasteful, and I'm pretty OCD about it.
1) One approach would be to match the InnerHtml string against a regular expression containing the keywords as a list of alternatives:
Imports System.Text.RegularExpressions
Dim keywords As New Regex("keyword1|keyword2|keyword3")
...
If keywords.IsMatch(HElement.InnerHtml) Then ...
This should work well if you know all your keywords beforehand.
2) An alternative approach would be to build a list of your keywords and then compare the InnerHtml string against each of the list's elements:
Dim keywords = {"keyword1", "keyword2", "keyword3"}
...
For Each keyword As String In keywords
If HElement.InnerHtml.Contains(keyword) Then ...
Next
Edit: The extension method suggested by Rob would result in more elegant code than the above approach #2, IMO.
You could write an Extension Method to string that provides a multi-input option, such as:
Public Module StringExtensionMethods
Private Sub New()
End Sub
<System.Runtime.CompilerServices.Extension> _
Public Function Contains(ByVal str As String, ByVal ParamArray values As String()) As Boolean
For Each value In values
If str.Contains(value) Then
Return True
End If
Next
Return False
End Function
End Module
You could then call that instead, as in your second example :)
Here's another extension method that cleans up the logic a little with LINQ:
<Extension()>
Public Function MultiContains(str As String, ParamArray values() As String) As Boolean
Return values.Any(Function(val) str.Contains(val))
End Function