The Join()
method joins the elements of an array using a specified separator.
Example
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// creates a string array.
string[] text = { "C#", "Java", "C++" };
// joins string with space between them
Console.WriteLine(String.Join(" ", text));
Console.ReadLine();
}
}
}
// Output: C# Java C++
Join() Syntax
The syntax of the string Join()
method is:
String.Join(String separator, String[] value, Int32 startIndex, Int32 count)
Here, Join()
is a method of class String
.
Join() Parameters
The Join()
method takes the following parameters:
- separator - the separator to join the elements
- value - an array of strings to join
- startIndex - the first item in value to join
- count - number of elements to join (starts from startIndex)
Join() Return Value
- returns a string that consists of the elements separated by the separator
Example 1: C# String Join()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// creates a string array.
string[] text = {"C#", "Java", "C++"};
// joins string with "/" between them
string result = String.Join("/", text);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
Output
C#/Java/C++
Here, the text elements "C#"
, "Java"
, and "C++"
to the Join()
are joined using the /
separator.
Example 2: Join() With Start Index and Count
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// Creating a string array
string[] text = {"C#", "Java", "C++", "Swift", "Go"};
// joins 2 strings from index 1
string s1 = String.Join("-", text, 1, 2);
Console.WriteLine(s1);
Console.ReadLine();
}
}
}
Output
Java-C++
In the above example, notice the line,
string s1 = String.Join("-", text, 1, 2);
Here,
1
- starting index of text to join (index of"Java"
)2
- number of elements to join