Case 1:
View code
Using System;
Class Program
{
Static Void Main ()
{
String [] Arr = { " One " ," Two " , " Three " };
Console. writeline ( String . Join ( " , " , Arr )); // "String" can be lowercase, or
Console. writeline (string. Join (" , " , Arr )); // "String" can be uppercase
}
}
Output result:
One, two, three
One, two, three
Case 2:
View code Using System;
Class Program
{
Static Void Main ()
{
// Problem: combine these words into lines in HTML
String [] Din1_urs = New String [] { " Aeolosaurus " ,
" Deinonychus " , " Jaxartosaurus " , " Segnosaurus " };
//Solution: Join with break tag.
StringHtml =String. Join ("<Br/> \ r \ n", Dinosaurs );
Console. writeline (HTML );
}
}
Output result:
Aeolosaurus <br/>
Deinonychus <br/>
Jaxartosaurus <br/>
Segnosaurus
Case 3:
View code Using System;
Using System. text;
Class Program
{
Static Void Main ()
{
String [] Catspecies = { " Aegean " , " Birman " , " Main coon " , " Nebulung " };
Console. writeline (combinea (catspecies ));
Console. writeline (combineb (catspecies ));
}
/// <Summary>
/// Combine strings with commas.
/// </Summary>
Static String Combinea ( String [] ARR)
{
Return String . Join ( " , " , Arr );
}
/// <Summary>
/// Combine strings with commas.
/// </Summary>
Static String Combineb ( String [] ARR)
{
Stringbuilder builder = New Stringbuilder ();
Foreach ( String S In ARR)
{
Builder. append (s). append ( " , " );
}
Return Builder. tostring (). trimend ( New Char [] { ' , ' });
}
}
Output result:
Aegean, Birman, main coon, nebulung
Aegean, Birman, main coon, nebulung
Case 4:
View code Using System;
Class Program
{
Static Void Main ()
{
Try
{
String Bug = String . Join (Null , Null ); // Null arguments are bad
}
Catch (Exception ex)
{
Console. writeline (Ex );
}
}
}
Output result:
System. argumentnullexception: value cannot be null.
Parameter Name: Value
Case 5:
View code Using System;
Using System. Collections. Generic;
Class Program
{
Static Void Main ()
{
// List of cities
List < String > Cities = New List < String > ();
Cities. Add ( " New York " );
Cities. Add ( " Mumbai " );
Cities. Add ( " Berlin " );
Cities. Add ( " Istanbul " );
//Join strings into one CSV line
StringLine =String. Join (",", Cities. toarray ());
Console. writeline (line );
}
}
New York, Mumbai, Berlin, Istanbul
Conclusion: compared with the stringbuilder method, the join method has a much higher performance. Some people have tested 1000000 pieces of data. The two methods are time-consuming:
String. Join:157 MS
Stringbuilder append method:270 MS