Create a string and append text to it - vb.net

Funny, I had a textbox and I could append strings to it.
But now I create a string like this:
Dim str As String = New String("")
And I want to append to it other strings. But there is no function for doing so. What am I doing wrong?

Concatenate with & operator
Dim str as String 'no need to create a string instance
str = "Hello " & "World"
You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.
Concatenate with String.Concat()
str = String.Concat("Hello ", "World")
Useful when concatenating array of strings
StringBuilder.Append()
When concatenating large amounts of strings use StringBuilder, it will result in much better performance.
Dim sb as new System.Text.StringBuilder()
str = sb.Append("Hello").Append(" ").Append("World").ToString()
Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.

Another way to do this is to add the new characters to the string as follows:
Dim str As String
str = ""
To append text to your string this way:
str = str & "and this is more text"

Use the string concatenation operator:
Dim str As String = New String("") & "some other string"
Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.
This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.
See "How to: Concatenate Multiple Strings" for more information on both methods.

Related

vb.net Interpolated Strings

I was chastised by a professional developer with a lot of years of experience for Hard Coding my DB name
OK I get it we sometimes carry our bad codding habits with us till we learn the correct way to code
I have finally learned to use Interpolated Strings (personal view they are not pretty)
My Question involves the two Sub's posted below GetDB runs first then HowMany is called from GetDB
Sorry for stating the obvious my reason is I think that NewWord.db gets declared in GetDB and works in HowMany without the same construction Just a Wild Guess
Notice NO $ or quotation used in HowMany
Both Sub's produce desired results
The question is Why don't both statements need to be constructed the same?
Public Sub HowMany()
'Dim dbName As String = "NewWord.db"
Dim conn As New SQLiteConnection("Data Source ='{NewWord.db}';Version=3;")
tot = dgvOne.RowCount ' - 1
tbMessage.Text = "DGV has " & tot.ToString & " Rows"
End Sub
Private Sub GetDB()
Dim str2 As String
Dim s1 As Integer
'Dim dbName As String = "NewWord.db"
Using conn As New SQLiteConnection($"Data Source = '{"NewWord.db"}' ;Version=3;")
conn.Open()
That second method is a ridiculous and pointless use of string interpolation. What could possibly be the point of inserting a literal String into a literal String? The whole point is that you can insert values determined at run time. That second code is equivalent to using:
"Data Source = '" & "NewWord.db" & "' ;Version=3;"
What's the point of that? The idea is that you retrieve your database name from somewhere at run time, e.g. your config file, and then insert that into the template String, e.g.
Dim dbName = GetDbNameFromExternalFile()
Using conn As New SQLiteConnection($"Data Source = '{dbName}' ;Version=3;")
Now the user can edit that external file to change the database name after deploying the application. How could they change the name in your code?
To be clear, string interpolation is just native language support for the String.Format method. You can see that if you make a mistake that generates an exception and the that exception will refer to the String.Format method. In turn, String.Format is a way to make code that multiple values into a long template easier to read than if multiple concatenation operators were used.
Having lots of quotes and ampersands makes code hard to read and error-prone. I've lost count of the number of times people miss a single quote or a space or the like in a String because they couldn't read there messy code. Personally, I'll rarely use two concatenation operators in the same expression and never three. I'll do this:
Dim str = "some text" & someVar
but I'll rarely do this:
Dim str = "some text" & someVar & "some more text"
and I'll never do this:
Dim str = "some text" & someVar & "some more text" & someOtherVar
Before string interpolation, I would use String.Format:
Dim str = String.Format("some text{0}some more text{1}", someVar, someOtherVar)
Nowadays, I'll generally use string interpolation:
Dim str = $"some text{someVar}some more text{someOtherVar}"
Where I may still use String.Format over string interpolation is if one value is getting inserted in multiple places and/or where the text template and/or the expressions are long so that I can break the whole thing over multiple lines, e.g.
Dim str = String.Format("some text{0}some more text{1}yet more text{0}",
someVar,
someOtherVar)
I have no idea what NewWord.db is so I made a class to represent it.
Public Class NewWord
Public Shared Property db As String = "The db Name"
End Class
HowMany is not a very good name for your sub. Try to use more descriptive names.
The first sub doesn't even use the connection. The connection string in that code is a literal string. It will not consider NewWord.db as a variable. You will not notice this because you never attempt to open the connection. In my version you check the connection string with a Debug.Print.
I changed the last line to use and interpolated string. It is not necessary to call .ToString on tot.
Private Sub DisplayGridCount()
Dim conn As New SQLiteConnection("Data Source ='{NewWord.db}';Version=3;")
Debug.Print(conn.ConnectionString)
Dim tot = DataGridView1.RowCount
TextBox1.Text = $"DGV has {tot} Rows"
End Sub
The second snippet starts off with 2 unused variables. I deleted them. Again, the Debug.Print to show the difference in the 2 strings.
Private Sub TestConnection()
Using conn As New SQLiteConnection($"Data Source = '{NewWord.db}' ;Version=3;")
Debug.Print(conn.ConnectionString)
'conn.Open()
End Using
End Sub
As to where to store connection strings see https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/protecting-connection-information and Where to store Connection String

Vb.net, replace any number at the end of a string with a placeholder

I have many strings that have numbers at the end. The numbers can be of any size, for example:
myvar123
mysecondvar3
mythirdvar219107
The strings can have numbers even inside the name, not only at the end.
for example:
my2varable123
some123variable9480395
I would need to replace any number at the END with a placeholder. (NOT those inside the varname.)
for example:
my2varable123 should become: my2variable%placeholder%
some123variable9480395 should become: some123variable%placeholder%
The only way that comes to my mind is to go through the string using .right() and remove the char if it is numeric until I find the first non numeric char. Then in the end append the placeholder, but it looks like a lot of work for a rather simply problem.
Is there a better way to do this?
You could use a Regex for this.
Dim str As String = "some123variable9480395"
Dim pattern As String = "\d+$"
Dim replacement As String = "%placeholder%"
Dim rgx As Regex = New Regex(pattern)
Dim result As String = rgx.Replace(str, replacement)

visual studio split function issue

I try to call split function on visual studio as below and i expect it return me 2 item in array after split, but vb return 5 results from my coding. It is consider vb issue or my coding issue?
Whole string is "NAME":"ALICE"
Dim a As String = """NAME"":""ALICE"""
Dim b() As String = a.Split(""":")
Output I expected in array after split
(1) "NAME
(2) "ALICE"
You were using this overload of String.Split(Char[]). Note that takes an array of characters. String is convertible to an array of characters (and that's why you could compile) but it is not equal. Try putting Option Strict On at the top of your code. It won't compile as you have it anymore :)
When passing a single string, each character in the string is used to split. Including each " in your argument, ":. It will split on " and :. You can get around it by passing a string array to Split using this overload of String.Split(String[], SplitStringOptions). Pass a single element array like this
Dim b = a.Split({""":"}, StringSplitOptions.RemoveEmptyEntries)
Yes, that is exactly as you said,
"NAME
"ALICE"
Do you want to get rid of the quotes in the result? You can do this
Dim b = a.Split({":", """"}, StringSplitOptions.RemoveEmptyEntries)
Then it's this,
NAME
ALICE
Dim a As String = """NAME"":""ALICE"""
Dim b() As String = a.Split(":")
this is how it evaluates

How to separate data with a comma

For example, I'm having a two set of vars with data type of string:
users = "Admin, Staff"
pass = "202cb9, caf1a"
These are vars with only normal string data type. The two vars above is generated, so I could only get these kind of data. The question is:
How can I separate those data by the commas (like Admin -> 202cb9, Staff -> caf1a) and then store them into an array.
users_array(0) = "Admin"
users_array(1) = "Staff"
pass_array(0) = "202cb9"
pass_array(1) = "caf1a"
Thank you.
You can use users.Split(New Char() {","c}) as in this link.
http://www.dotnetperls.com/split-vbnet
I have two options to solve this problem:
Dim users_array() As String = users.Split(New String() {", "}, StringSplitOptions.RemoveEmptyEntries)
and:
Dim pass_array() As String = Split(users, ", ")
IMO, it is better to use ,<space> as a separator string instead of just ,, to avoid getting <space>staff at index 1.
Here the first solution works for both C# and VB.Net and second one is specific to VB.Net.
User String.Split to break strings apart on a specific character. It returns an array.

How to split in VB.NET

I am using VB.NET code.
I have got the below string.
http://localhost:3282/ISS/Training/SearchTrainerData.aspx
Now I want to split the above string with "/" as well. I want to store the value SearchTrainerData.aspx in a variable.
In my case
Dim str as String
str = "SearchTrainerData.aspx"
What would be the code which will split the above string and further store it in a variable?
Try to use the function String.Split.
Your "string" is obviously a URL which means you should use the System.Uri class.
Dim url As Uri = New Uri("http://localhost:3282/ISS/Training/SearchTrainerData.aspx")
Dim segments As String() = url.Segments
Dim str As String = segments(segments.Length - 1)
This will also allow you to get all kinds of other interesting information about your "string" without resorting to manual (and error-prone) parsing.
The Split function takes characters, which VB.NET represents by appending a 'c' to the end of a one-character string:
Dim sentence = "http://localhost:3282/ISS/Training/SearchTrainerData.aspx"
Dim words = sentence.Split("/"c)
Dim lastWord = words(words.length - 1)
I guess what you are actually looking for is the System.Uri Class. Which makes all string splitting that you are looking for obsolete.
MSDN Documentation for System.Uri
Uri url = new Uri ("http://...");
String[] parts = url.Segments;
Use split(). You call it on the string instance, passing in a char array of the delimiters, and it returns to you an array of strings. Grab the last element to get your "SearchTrainerData.aspx."