C# String Join() Method
The Join()
method in C# is used to concatenate an array of strings into a single string, with a specified separator between each element of the array. It returns a new string that contains the concatenated elements of the array, separated by the specified separator.
The syntax of the Join()
method is as follows:
string.Join(separator, values);
Here, separator
is the string to use as a separator between the elements of the array, and values
is the array of strings to concatenate.
For example, to concatenate an array of strings with a comma separator, you can use the following code:
string[] fruits = { "apple", "banana", "cherry" }; string result = string.Join(",", fruits); Console.WriteLine(result); // Output: "apple,banana,cherry"
In this example, the Join()
method is used to concatenate the array of strings { "apple", "banana", "cherry" }
with a comma separator. The resulting string "apple,banana,cherry"
is then assigned to the result
variable and printed to the console using the WriteLine()
method.
You can use any string as a separator, including an empty string. For example, to concatenate an array of strings with no separator, you can use the following code:
string[] fruits = { "apple", "banana", "cherry" }; string result = string.Join("", fruits); Console.WriteLine(result); // Output: "applebananacherry"
In this example, the Join()
method is used to concatenate the array of strings { "apple", "banana", "cherry" }
with an empty separator. The resulting string "applebananacherry"
is then assigned to the result
variable and printed to the console.
You can also use the Join()
method to concatenate a subset of the elements of an array, starting from a specified index and including a specified number of elements. To do this, you can use the following syntax:
string.Join(separator, values, startIndex, count);
Here, startIndex
is the zero-based index of the first element to concatenate, and count
is the number of elements to concatenate. For example:
string[] fruits = { "apple", "banana", "cherry", "date", "elderberry" }; string result = string.Join(",", fruits, 2, 3); Console.WriteLine(result); // Output: "cherry,date,elderberry"
In this example, the Join()
method is used to concatenate the three elements starting from the index 2
of the array { "apple", "banana", "cherry", "date", "elderberry" }
with a comma separator. The resulting string "cherry,date,elderberry"
is then assigned to the result
variable and printed to the console.