Section13.1:+Operator
strings1=”string1″;
strings2=”string2″;
strings3=s1+s2;//”string1string2″
Section 13.2: Concatenate strings using System.Text.StringBuilder
Concatenating strings using a StringBuildercan offer performance advantages over simple string concatenation using+.Thisisduetothewaymemoryisallocated.Stringsarereallocatedwitheachconcatenation,StringBuilders allocate memory in blocks only reallocating when the current block is exhausted. This can make a huge difference when doing a lot of small concatenations.
StringBuildersb=newStringBuilder();
for(inti=1;i<=5;i++)
{
sb.Append(i);
sb.Append(“”);
}
Console.WriteLine(sb.ToString());//”12345″
CallstoAppend()canbedaisychained,becauseitreturnsareferencetotheStringBuilder:
StringBuildersb=newStringBuilder();
sb.Append(“somestring”)
.Append(“anotherstring”);
Section13.3:ConcatstringarrayelementsusingString.Join
TheString.Joinmethodcanbeusedtoconcatenatemultipleelementsfromastringarray.
string[]value={“apple”,”orange”,”grape”,”pear”};
stringseparator=”,”;
stringresult=String.Join(separator,value,1,2);
Console.WriteLine(result);
Producesthefollowingoutput:”orange,grape”
ThisexampleusestheString.Join(String,String[],Int32,Int32)overload,whichspecifiesthestartindex and count on top of the separator and value.
IfyoudonotwishtousethestartIndexandcountoverloads,youcanjoinallstringgiven.Like this:
string[]value={“apple”,”orange”,”grape”,”pear”};
stringseparator=”,”;
stringresult=String.Join(separator,value); Console.WriteLine(result);
whichwillproduce;
apple,orange,grape,pear
Section13.4:Concatenationoftwostringsusing$
$providesaneasyandaconcisemethodtoconcatenatemultiple strings.
varstr1=”text1″;
varstr2=””;
varstr3=”text3″;
stringresult2=$”{str1}{str2}{str3}”;//”text1text3″
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024