Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a string and append text to it

Tags:

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?

like image 208
Voldemort Avatar asked Mar 19 '11 05:03

Voldemort


People also ask

How do I append to a string?

You can use the '+' operator to append two strings to create a new string. There are various ways such as using join, format, string IO, and appending the strings with space.

What does it mean to append a string?

Concatenation of strings refers to joining two or more strings together, as if links in a chain. You can concatenate in any order, such as concatenating str1 between str2 and str3 . Appending strings refers to appending one or more strings to the end of another string.


2 Answers

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.

like image 190
Philip Fourie Avatar answered Oct 03 '22 06:10

Philip Fourie


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" 
like image 43
TJTex Avatar answered Oct 03 '22 07:10

TJTex