String.Join Method
Overloads
| Join(String, String[], Int32, Int32) |
Concatenates the specified elements of a string array, using the specified separator between each element. |
| Join(String, String[]) |
Concatenates all the elements of a string array, using the specified separator between each element. |
| Join(String, Object[]) |
Concatenates the elements of an object array, using the specified separator between each element. |
| Join(String, IEnumerable<String>) |
Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. |
| Join<T>(String, IEnumerable<T>) |
Concatenates the members of a collection, using the specified separator between each member. |
Join(String, String[], Int32, Int32)
Concatenates the specified elements of a string array, using the specified separator between each element.
public static string Join (string separator, string[] value, int startIndex, int count);
Parameters
- separator
- String
The string to use as a separator. separator is included in the returned string only if value has more than one element.
- value
- String[]
An array that contains the elements to concatenate.
- startIndex
- Int32
The first element in value to use.
- count
- Int32
The number of elements of value to use.
Returns
A string that consists of the strings in value delimited by the separator string.
-or-
Empty if count is zero, value has no elements, or separator and all the elements of value are Empty.
Exceptions
value is null.
startIndex or count is less than 0.
-or-
startIndex plus count is greater than the number of elements in value.
Out of memory.
Examples
The following example concatenates two elements from an array of names of fruit.
// Sample for String.Join(String, String[], int int)
using System;
class Sample {
public static void Main() {
String[] val = {"apple", "orange", "grape", "pear"};
String sep = ", ";
String result;
Console.WriteLine("sep = '{0}'", sep);
Console.WriteLine("val[] = {{'{0}' '{1}' '{2}' '{3}'}}", val[0], val[1], val[2], val[3]);
result = String.Join(sep, val, 1, 2);
Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result);
}
}
/*
This example produces the following results:
sep = ', '
val[] = {'apple' 'orange' 'grape' 'pear'}
String.Join(sep, val, 1, 2) = 'orange, grape'
*/
Remarks
For example, if separator is ", " and the elements of value are "apple", "orange", "grape", and "pear", Join(separator, value, 1, 2) returns "orange, grape".
If separator is null, an empty string (String.Empty) is used instead. If any element in value is null, an empty string is used instead.
- See also
Join(String, String[])
Concatenates all the elements of a string array, using the specified separator between each element.
public static string Join (string separator, params string[] value);
Parameters
- separator
- String
The string to use as a separator. separator is included in the returned string only if value has more than one element.
- value
- String[]
An array that contains the elements to concatenate.
Returns
A string that consists of the elements in value delimited by the separator string. If value is an empty array, the method returns Empty.
Exceptions
value is null.
Examples
The following example demonstrates the Join method.
using System;
public class JoinTest {
public static void Main() {
Console.WriteLine(MakeLine(0, 5, ", "));
Console.WriteLine(MakeLine(1, 6, " "));
Console.WriteLine(MakeLine(9, 9, ": "));
Console.WriteLine(MakeLine(4, 7, "< "));
}
private static string MakeLine(int initVal, int multVal, string sep) {
string [] sArr = new string [10];
for (int i = initVal; i < initVal + 10; i++)
sArr[i - initVal] = String.Format("{0,-3}", i * multVal);
return String.Join(sep, sArr);
}
}
// The example displays the following output:
// 0 , 5 , 10 , 15 , 20 , 25 , 30 , 35 , 40 , 45
// 6 12 18 24 30 36 42 48 54 60
// 81 : 90 : 99 : 108: 117: 126: 135: 144: 153: 162
// 28 < 35 < 42 < 49 < 56 < 63 < 70 < 77 < 84 < 91
Remarks
For example, if separator is ", " and the elements of value are "apple", "orange", "grape", and "pear", Join(separator, value)returns "apple, orange, grape, pear".
If separator is null, an empty string (String.Empty) is used instead. If any element in value is null, an empty string is used instead.
- See also
Join(String, Object[])
Concatenates the elements of an object array, using the specified separator between each element.
[System.Runtime.InteropServices.ComVisible(false)]
public static string Join (string separator, params object[] values);
Parameters
- separator
- String
The string to use as a separator. separator is included in the returned string only if values has more than one element.
- values
- Object[]
An array that contains the elements to concatenate.
Returns
A string that consists of the elements of values delimited by the separator string. If values is an empty array, the method returns Empty.
Exceptions
values is null.
Examples
The following example uses the Sieve of Eratosthenes algorithm to calculate the prime numbers that are less than or equal to 100. It assigns the result to a integer array, which it then passes to the Join(String, Object[]) method.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
int maxPrime = 100;
int[] primes = GetPrimes(maxPrime);
Console.WriteLine("Primes less than {0}:", maxPrime);
Console.WriteLine(" {0}", String.Join(" ", primes));
}
private static int[] GetPrimes(int maxPrime)
{
Array values = Array.CreateInstance(typeof(int),
new int[] { maxPrime - 1}, new int[] { 2 });
// Use Sieve of Eratosthenes to determine prime numbers.
for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
{
if ((int) values.GetValue(ctr) == 1) continue;
for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
if (ctr * multiplier <= maxPrime)
values.SetValue(1, ctr * multiplier);
}
List<int> primes = new List<int>();
for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
if ((int) values.GetValue(ctr) == 0)
primes.Add(ctr);
return primes.ToArray();
}
}
// The example displays the following output:
// Primes less than 100:
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Remarks
If separator is null or if any element of values other than the first element is null, an empty string (String.Empty) is used instead. See the Notes for Callers section if the first element of values is null.
Join(String, Object[]) is a convenience method that lets you concatenate each element in an object array without explicitly converting its elements to strings. The string representation of each object in the array is derived by calling that object's ToString method.
Notes to Callers
If the first element of values is null, the Join(String, Object[]) method does not concatenate the elements in values but instead returns Empty. A number of workarounds for this issue are available. The easiest is to assign a value of Empty to the first element of the array, as the following example shows.
object[] values = { null, "Cobb", 4189, 11434, .366 };
if (values[0] == null) values[0] = String.Empty;
Console.WriteLine(String.Join("|", values));
// The example displays the following output:
// |Cobb|4189|11434|0.366
- See also
Join(String, IEnumerable<String>)
Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member.
[System.Runtime.InteropServices.ComVisible(false)]
public static string Join (string separator, System.Collections.Generic.IEnumerable<string> values);
Parameters
- separator
- String
The string to use as a separator.separator is included in the returned string only if values has more than one element.
- values
- IEnumerable<String>
A collection that contains the strings to concatenate.
Returns
A string that consists of the members of values delimited by the separator string. If values has no members, the method returns Empty.
Exceptions
values is null.
Examples
The following example uses the Sieve of Eratosthenes algorithm to calculate the prime numbers that are less than or equal to 100. It assigns the result to a List<T> object of type String, which it then passes to the Join(String, IEnumerable<String>) method.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
int maxPrime = 100;
List<int> primes = GetPrimes(maxPrime);
Console.WriteLine("Primes less than {0}:", maxPrime);
Console.WriteLine(" {0}", String.Join(" ", primes));
}
private static List<int> GetPrimes(int maxPrime)
{
Array values = Array.CreateInstance(typeof(int),
new int[] { maxPrime - 1}, new int[] { 2 });
// Use Sieve of Eratosthenes to determine prime numbers.
for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
{
if ((int) values.GetValue(ctr) == 1) continue;
for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
if (ctr * multiplier <= maxPrime)
values.SetValue(1, ctr * multiplier);
}
List<int> primes = new List<int>();
for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
if ((int) values.GetValue(ctr) == 0)
primes.Add(ctr);
return primes;
}
}
// The example displays the following output:
// Primes less than 100:
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Remarks
If separator is null, an empty string (String.Empty) is used instead. If any member of values is null, an empty string is used instead.
Join(String, IEnumerable<String>) is a convenience method that lets you concatenate each element in an IEnumerable(Of String)collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions. The following example passes a List(Of String) object that contains either the uppercase or lowercase letters of the alphabet to a lambda expression that selects letters that are equal to or greater than a particular letter (which, in the example, is "M"). The IEnumerable(Of String) collection returned by the Enumerable.Where method is passed to the Join(String, IEnumerable<String>) method to display the result as a single string.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
string output = String.Join(" ", GetAlphabet(true).Where( letter =>
letter.CompareTo("M") >= 0));
Console.WriteLine(output);
}
private static List<string> GetAlphabet(bool upper)
{
List<string> alphabet = new List<string>();
int charValue = upper ? 65 : 97;
for (int ctr = 0; ctr <= 25; ctr++)
alphabet.Add(Convert.ToChar(charValue + ctr).ToString());
return alphabet;
}
}
// The example displays the following output:
// M N O P Q R S T U V W X Y Z
- See also
Join<T>(String, IEnumerable<T>)
Concatenates the members of a collection, using the specified separator between each member.
[System.Runtime.InteropServices.ComVisible(false)]
public static string Join<T> (string separator, System.Collections.Generic.IEnumerable<T> values);
Type Parameters
- T
The type of the members of values.
Parameters
- separator
- String
The string to use as a separator.separator is included in the returned string only if values has more than one element.
- values
- IEnumerable<T>
A collection that contains the objects to concatenate.
Returns
A string that consists of the members of values delimited by the separator string. If values has no members, the method returns Empty.
Exceptions
values is null.
Examples
The following example uses the Sieve of Eratosthenes algorithm to calculate the prime numbers that are less than or equal to 100. It assigns the result to a List<T> object of type integer, which it then passes to the Join<T>(String, IEnumerable<T>) method.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
int maxPrime = 100;
List<int> primes = GetPrimes(maxPrime);
Console.WriteLine("Primes less than {0}:", maxPrime);
Console.WriteLine(" {0}", String.Join(" ", primes));
}
private static List<int> GetPrimes(int maxPrime)
{
Array values = Array.CreateInstance(typeof(int),
new int[] { maxPrime - 1}, new int[] { 2 });
// Use Sieve of Eratosthenes to determine prime numbers.
for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
{
if ((int) values.GetValue(ctr) == 1) continue;
for (int multiplier = ctr; multiplier <= maxPrime / 2; multiplier++)
if (ctr * multiplier <= maxPrime)
values.SetValue(1, ctr * multiplier);
}
List<int> primes = new List<int>();
for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
if ((int) values.GetValue(ctr) == 0)
primes.Add(ctr);
return primes;
}
}
// The example displays the following output:
// Primes less than 100:
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Remarks
If separator is null, an empty string (String.Empty) is used instead. If any member of values is null, an empty string is used instead.
Join<T>(String, IEnumerable<T>) is a convenience method that lets you concatenate each member of an IEnumerable<T>collection without first converting them to strings. The string representation of each object in the IEnumerable<T> collection is derived by calling that object's ToString method.
This method is particular useful with Language-Integrated Query (LINQ) query expressions. For example, the following code defines a very simple Animal class that contains the name of an animal and the order to which it belongs. It then defines a List<T> object that contains a number of Animal objects. The Enumerable.Where extension method is called to extract the Animal objects whose Order property equals "Rodent". The result is passed to the Join<T>(String, IEnumerable<T>) method.
using System;
using System.Collections.Generic;
using System.Linq;
public class Animal
{
public string Kind;
public string Order;
public Animal(string kind, string order)
{
this.Kind = kind;
this.Order = order;
}
public override string ToString()
{
return this.Kind;
}
}
public class Example
{
public static void Main()
{
List<Animal> animals = new List<Animal>();
animals.Add(new Animal("Squirrel", "Rodent"));
animals.Add(new Animal("Gray Wolf", "Carnivora"));
animals.Add(new Animal("Capybara", "Rodent"));
string output = String.Join(" ", animals.Where( animal =>
(animal.Order == "Rodent")));
Console.WriteLine(output);
}
}
// The example displays the following output:
// Squirrel Capybara
- See also
Applies to
.NET Core
.NET Framework
.NET Standard
Xamarin.Android
Xamarin.iOS
Xamarin.Mac
String.Join Method的更多相关文章
- C# string.join
String.Join 方法 平常工作中经常用到string.join()方法,在vs 2017用的运行时(System.Runtime, Version=4.2.0.0)中,共有九个(重载)方法. ...
- Python中字符串操作函数string.split('str1')和string.join(ls)
Python中的字符串操作函数split 和 join能够实现字符串和列表之间的简单转换, 使用 .split()可以将字符串中特定部分以多个字符的形式,存储成列表 def split(self, * ...
- 也谈string.Join和StringBuilder的性能比较
前几天在园子里面看到一篇讲StringBuilder性能的文章.文章里面给出了一个测试用例,比较StringBuilder.AppendJoin和String.Join的性能.根据该测试结果,&quo ...
- BCL中String.Join的实现
在开发中,有时候会遇到需要把一个List对象中的某个字段用一个分隔符拼成一个字符串的情况.比如在SQL语句的in条件中,我们通常需要把List<int>这样的对象转换为“1,2,3”这样的 ...
- c# String.Join 和 Distinct 方法 去除字符串中重复字符
1.在写程序中经常操作字符串,需要去重,以前我的用方式利用List集合和 contains去重复数据代码如下: string test="123,123,32,125,68,9565,432 ...
- String.Join的巧用
String.Join大大的方便了我们拼接字符串的处理. 1.普通用法:指定元素间的拼接符号 var ids = new List<int>(); for (int i = 0; i &l ...
- string.Join()的用法
List<string> list = new List<string>(); list.Add("I"); list.Add("Love&quo ...
- string.join加引号
columnsGen = string.Join(",", modelDictionary.Keys); valueGen = modelDictionary.Values.Agg ...
- String.Join 和 Distinct 方法 去除字符串中重复字符
Qualys项目中写到将ServerIP以“,”分割后插入数据库并将重复的IP去除后发送到服务器进行Scan,于是我写了下面的一段用来剔除重复IP: //CR#1796870 modify by v- ...
随机推荐
- Asp.NetCore依赖注入和管道方式的异常处理及日志记录
前言 在业务系统,异常处理是所有开发人员必须面对的问题,在一定程度上,异常处理的能力反映出开发者对业务的驾驭水平:本章将着重介绍如何在 WebApi 程序中对异常进行捕获,然后利用 Nlog ...
- Python编程从入门到实践笔记——列表简介
Python编程从入门到实践笔记——列表简介 #coding=utf-8 #列表——我的理解等于C语言和Java中的数组 bicycles = ["trek","cann ...
- 关于CSS引入方式的详细见解
关于CSS的发展史这里不做介绍.写博客的原因之一是想帮助那些与我一样喜欢纠结的初入前端的伙伴,希望自己写的帖子能对伙伴有些许帮助:原因之二这些帖子也算自己的一个知识的整理.现在还没有一定的顺序可循,但 ...
- 在嵌入式设备中使用 JavaScript 的前景
by Conmajia PC上的JavaScript已经发展到ECMAScript 6(ES6),马上ES10都快出来了(虽然还是草案),但是硬件上的JS却很少听说.这几年手持设备/可穿戴设备的发展非 ...
- DSAPI 网卡流量监控
这是一个非常有意思的趣味小功能,统计每个网卡的流量信息. Dim 网卡() As DSAPI.网络.网卡信息 = DSAPI.网络.获取本机所有网卡信息 While True Console.Clea ...
- composer windows下安装
composer windows安装 因要使用PhpSpreadsheet处理excel表格 选择composer安装 1. 下载Composer-Setup.exe 2.点击直接运行---选择ph ...
- ArcEngine ILabelEngineLayerProperties Expression 添加常量
ArcEngine实现复杂标注的时候,需要结合几个字段并将常量加载表达式中. 开始的时候发现VBScript需要采用“”来括起来常量才能在VB中正常使用,但是 ILabelEngineLayerPro ...
- Python 强制停止多线程运行
强制停止多线程运行 by:授客 QQ:1033553122 #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' ...
- Android项目实战(五十三):判断网络连接是否为有线状态(tv项目适配)
一般对于android手机,我们可以通过sdk提供的方法判断网络情况 /** * 获取当前的网络状态 :没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2 * 自定义 * * @p ...
- vue 外部字体图标使用,无须绝对路径引入办法
通常外部字体图标都在使用 iconfont ,这种图标在网上搜到一大把都是由于路径问题显示不出来,或者是显示个方块. 最近的项目中也碰到这个坑爸的问题,总结一下解决办法: 和 webpack.conf ...