String.Join Metodo

Definizione

Concatena gli elementi di una matrice specificata o i membri di una raccolta, usando tra gli elementi o i membri il separatore specificato.

Overload

Join(Char, Object[])

Concatena le rappresentazioni di stringa di una matrice di oggetti, usando il separatore specificato tra ogni membro.

Join(Char, String[])

Concatena una matrice di stringhe, usando il separatore specificato tra ogni membro.

Join(String, IEnumerable<String>)

Concatena i membri di una raccolta IEnumerable<T> costruita di tipo String, usando tra i membri il separatore specificato.

Join(String, Object[])

Concatena gli elementi di una matrice di oggetti, usando tra gli elementi il separatore specificato.

Join(String, String[])

Concatena tutti gli elementi di una matrice di stringhe, usando tra gli elementi il separatore specificato.

Join(Char, String[], Int32, Int32)

Concatena una matrice di stringhe, usando il separatore specificato tra ogni membro, a partire dall'elemento in value presente nella posizione di startIndex e concatenando fino a count elementi.

Join(String, String[], Int32, Int32)

Concatena gli elementi specificati di una matrice di stringhe, usando tra gli elementi il separatore specificato.

Join<T>(Char, IEnumerable<T>)

Concatena i membri di una raccolta, usando tra i membri il separatore specificato.

Join<T>(String, IEnumerable<T>)

Concatena i membri di una raccolta, usando tra i membri il separatore specificato.

Join(Char, Object[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Concatena le rappresentazioni di stringa di una matrice di oggetti, usando il separatore specificato tra ogni membro.

public:
 static System::String ^ Join(char separator, ... cli::array <System::Object ^> ^ values);
public static string Join (char separator, params object?[] values);
public static string Join (char separator, params object[] values);
static member Join : char * obj[] -> string
Public Shared Function Join (separator As Char, ParamArray values As Object()) As String

Parametri

separator
Char

Carattere da usare come separatore. separator è incluso solo nella stringa restituita solo se value presenta più di un elemento.

values
Object[]

Matrice di oggetti le cui rappresentazioni di stringa verranno concatenate.

Restituisce

Stringa costituita dagli elementi di values delimitati dal carattere separator.

-oppure-

Empty se values ha zero elementi.

Eccezioni

value è null.

La lunghezza della stringa risultante supera la lunghezza massima consentita (Int32.MaxValue).

Si applica a

Join(Char, String[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Concatena una matrice di stringhe, usando il separatore specificato tra ogni membro.

public:
 static System::String ^ Join(char separator, ... cli::array <System::String ^> ^ value);
public static string Join (char separator, params string?[] value);
public static string Join (char separator, params string[] value);
static member Join : char * string[] -> string
Public Shared Function Join (separator As Char, ParamArray value As String()) As String

Parametri

separator
Char

Carattere da usare come separatore. separator è incluso solo nella stringa restituita solo se value presenta più di un elemento.

value
String[]

Matrice di stringhe da concatenare.

Restituisce

Stringa costituita dagli elementi di value delimitati dal carattere separator.

-oppure-

Empty se value ha zero elementi.

Eccezioni

value è null.

La lunghezza della stringa risultante supera la lunghezza massima consentita (Int32.MaxValue).

Si applica a

Join(String, IEnumerable<String>)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Concatena i membri di una raccolta IEnumerable<T> costruita di tipo String, usando tra i membri il separatore specificato.

public:
 static System::String ^ Join(System::String ^ separator, System::Collections::Generic::IEnumerable<System::String ^> ^ values);
public static string Join (string separator, System.Collections.Generic.IEnumerable<string> values);
public static string Join (string? separator, System.Collections.Generic.IEnumerable<string?> values);
[System.Runtime.InteropServices.ComVisible(false)]
public static string Join (string separator, System.Collections.Generic.IEnumerable<string> values);
static member Join : string * seq<string> -> string
[<System.Runtime.InteropServices.ComVisible(false)>]
static member Join : string * seq<string> -> string
Public Shared Function Join (separator As String, values As IEnumerable(Of String)) As String

Parametri

separator
String

Stringa da usare come separatore.separator è incluso solo nella stringa restituita solo se values presenta più di un elemento.

values
IEnumerable<String>

Raccolta che contiene le stringhe da concatenare.

Restituisce

Stringa costituita dagli elementi di values delimitati dalla stringa separator.

-oppure-

Empty se values ha zero elementi.

Attributi

Eccezioni

values è null.

La lunghezza della stringa risultante supera la lunghezza massima consentita (Int32.MaxValue).

Esempio

Nell'esempio seguente viene usato l'algoritmo Sieve of Eratosthenes per calcolare i numeri primi minori o uguali a 100. Assegna il risultato a un List<T> oggetto di tipo String, che quindi passa al Join(String, IEnumerable<String>) metodo .

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
open System

let getPrimes maxPrime =
    let values = Array.CreateInstance(typeof<int>, [| maxPrime - 1 |], [| 2 |])
    // Use Sieve of Eratosthenes to determine prime numbers.
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 |> float |> sqrt |> ceil |> int do
        if values.GetValue i :?> int <> 1 then
            for multiplier = i to maxPrime / 2 do
                if i * multiplier <= maxPrime then
                    values.SetValue(1, i * multiplier)

    let primes = ResizeArray()
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
        if values.GetValue i :?> int = 0 then
            primes.Add i
    primes

let maxPrime = 100
let primes = getPrimes maxPrime
printfn $"Primes less than {maxPrime}:"
printfn $"""   {String.Join(" ", 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
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim maxPrime As Integer = 100
      Dim primes As List(Of String) = GetPrimes(maxPrime)
      Console.WriteLine("Primes less than {0}:", maxPrime)
      Console.WriteLine("   {0}", String.Join(" ", primes))
   End Sub
   
   Private Function GetPrimes(maxPrime As Integer) As List(Of String)
      Dim values As Array = Array.CreateInstance(GetType(Integer), _
                              New Integer() { maxPrime - 1}, New Integer(){ 2 }) 
        ' Use Sieve of Eratosthenes to determine prime numbers.
      For ctr As Integer = values.GetLowerBound(0) To _
                           CInt(Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))))
         If CInt(values.GetValue(ctr)) = 1 Then Continue For
         
         For multiplier As Integer = ctr To maxPrime \ 2
            If ctr * multiplier <= maxPrime Then values.SetValue(1, ctr * multiplier)
         Next   
      Next      
      
      Dim primes As New List(Of String)
      For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0)
         If CInt(values.GetValue(ctr)) = 0 Then primes.Add(ctr.ToString())
      Next            
      Return primes
   End Function   
End Module
' 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

Commenti

Se separator è null, viene invece usata una stringa vuota (String.Empty). Se un membro di values è null, viene utilizzata invece una stringa vuota.

Join(String, IEnumerable<String>) è un metodo pratico che consente di concatenare ogni elemento in una IEnumerable(Of String) raccolta senza prima convertire gli elementi in una matrice di stringhe. È particolarmente utile con le espressioni di query LINQ (Language-Integrated Query). Nell'esempio seguente viene passato un List(Of String) oggetto contenente le lettere maiuscole o minuscole dell'alfabeto a un'espressione lambda che seleziona lettere uguali o maggiori di una particolare lettera (che nell'esempio è "M"). La IEnumerable(Of String) raccolta restituita dal Enumerable.Where metodo viene passata al Join(String, IEnumerable<String>) metodo per visualizzare il risultato come singola stringa.

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(((char)(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
// This F# example uses Seq.filter instead of Linq.
open System

let getAlphabet upper =
    let charValue = if upper then 65 else 97
    seq {
        for i = 0 to 25 do
            charValue + i
            |> char
            |> string
    }

String.Join(" ", getAlphabet true |> Seq.filter (fun letter -> letter.CompareTo "M" >= 0))
|> printfn "%s"

// The example displays the following output:
//      M N O P Q R S T U V W X Y Z
Imports System.Collections.Generic
Imports System.Linq

Module modMain
   Public Sub Main()
      Dim output As String = String.Join(" ", GetAlphabet(True).Where(Function(letter) _
                                                         letter >= "M"))
        
      Console.WriteLine(output)                                     
   End Sub
   
   Private Function GetAlphabet(upper As Boolean) As List(Of String)
      Dim alphabet As New List(Of String)
      Dim charValue As Integer = CInt(IIf(upper, 65, 97))
      For ctr As Integer = 0 To 25
         alphabet.Add(ChrW(charValue + ctr).ToString())
      Next
      Return alphabet 
   End Function
End Module
' The example displays the following output:
'      M N O P Q R S T U V W X Y Z

Vedi anche

Si applica a

Join(String, Object[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Concatena gli elementi di una matrice di oggetti, usando tra gli elementi il separatore specificato.

public:
 static System::String ^ Join(System::String ^ separator, ... cli::array <System::Object ^> ^ values);
public static string Join (string separator, params object[] values);
public static string Join (string? separator, params object?[] values);
[System.Runtime.InteropServices.ComVisible(false)]
public static string Join (string separator, params object[] values);
static member Join : string * obj[] -> string
[<System.Runtime.InteropServices.ComVisible(false)>]
static member Join : string * obj[] -> string
Public Shared Function Join (separator As String, ParamArray values As Object()) As String

Parametri

separator
String

Stringa da usare come separatore. separator è incluso solo nella stringa restituita solo se values presenta più di un elemento.

values
Object[]

Matrice contenente gli elementi da concatenare.

Restituisce

Stringa costituita dagli elementi di values delimitati dalla stringa separator.

-oppure-

Empty se values ha zero elementi.

-oppure-

Solo .NET Framework: Empty se il primo elemento di values è null.

Attributi

Eccezioni

values è null.

La lunghezza della stringa risultante supera la lunghezza massima consentita (Int32.MaxValue).

Esempio

Nell'esempio seguente viene usato l'algoritmo Sieve of Eratosthenes per calcolare i numeri primi minori o uguali a 100. Assegna il risultato a una matrice integer, che quindi passa al Join(String, Object[]) metodo .

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
open System

let getPrimes maxPrime =
    let values = Array.CreateInstance(typeof<int>, [| maxPrime - 1 |], [| 2 |])
    // Use Sieve of Eratosthenes to determine prime numbers.
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 |> float |> sqrt |> ceil |> int do
        if values.GetValue i :?> int <> 1 then
            for multiplier = i to maxPrime / 2 do
                if i * multiplier <= maxPrime then
                    values.SetValue(1, i * multiplier)

    [| for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
        if values.GetValue i :?> int = 0 then
            i |]

let maxPrime = 100
let primes = getPrimes maxPrime
printfn $"Primes less than {maxPrime}:"
printfn $"""   {String.Join(" ", 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
Module Example
   Public Sub Main()
      Dim maxPrime As Integer = 100
      Dim primes() As Integer = GetPrimes(maxPrime)
      Console.WriteLine("Primes less than {0}:", maxPrime)
      Console.WriteLine("   {0}", String.Join(" ", primes))
   End Sub
   
   Private Function GetPrimes(maxPrime As Integer) As Integer()
      Dim values As Array = Array.CreateInstance(GetType(Integer), _
                              New Integer() { maxPrime - 1}, New Integer(){ 2 }) 
        ' Use Sieve of Eratosthenes to determine prime numbers.
      For ctr As Integer = values.GetLowerBound(0) To _
                           CInt(Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))))
         If CInt(values.GetValue(ctr)) = 1 Then Continue For
         
         For multiplier As Integer = ctr To maxPrime \ 2
            If ctr * multiplier <= maxPrime Then values.SetValue(1, ctr * multiplier)
         Next   
      Next      
      
      Dim primes As New System.Collections.Generic.List(Of Integer)
      For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0)
         If CInt(values.GetValue(ctr)) = 0 Then primes.Add(ctr)
      Next            
      Return primes.ToArray()
   End Function   
End Module
' 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

Commenti

Se separator è null o se un elemento diverso values dal primo elemento è null, viene utilizzata una stringa vuota (String.Empty). Vedere la sezione Notes for Callers se il primo elemento di values è null.

Join(String, Object[]) è un metodo pratico che consente di concatenare ogni elemento in una matrice di oggetti senza convertire in modo esplicito i relativi elementi in stringhe. La rappresentazione di stringa di ogni oggetto nella matrice è derivata chiamando il metodo dell'oggetto ToString .

Note per i chiamanti

Solo .NET Framework: se il primo elemento di values è null, il Join(String, Object[]) metodo non concatena gli elementi in values ma restituisce Emptyinvece . Sono disponibili diverse soluzioni alternative per questo problema. Il più semplice consiste nell'assegnare un valore di Empty al primo elemento della matrice, come illustrato nell'esempio seguente.

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
let values: obj[] = [| null; "Cobb"; 4189; 11434; 0.366 |]
if values[0] = null then 
   values[0] <- String.Empty
printfn $"""{String.Join("|", values)}"""

// The example displays the following output:
//      |Cobb|4189|11434|0.366
Dim values() As Object = { Nothing, "Cobb", 4189, 11434, .366 }
If values(0) Is Nothing Then values(0) = String.Empty
Console.WriteLine(String.Join("|", values))
' The example displays the following output:
'      |Cobb|4189|11434|0.366

Vedi anche

Si applica a

Join(String, String[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Concatena tutti gli elementi di una matrice di stringhe, usando tra gli elementi il separatore specificato.

public:
 static System::String ^ Join(System::String ^ separator, ... cli::array <System::String ^> ^ value);
public:
 static System::String ^ Join(System::String ^ separator, cli::array <System::String ^> ^ value);
public static string Join (string separator, params string[] value);
public static string Join (string? separator, params string?[] value);
public static string Join (string separator, string[] value);
static member Join : string * string[] -> string
Public Shared Function Join (separator As String, ParamArray value As String()) As String
Public Shared Function Join (separator As String, value As String()) As String

Parametri

separator
String

Stringa da usare come separatore. separator è incluso solo nella stringa restituita solo se value presenta più di un elemento.

value
String[]

Matrice contenente gli elementi da concatenare.

Restituisce

Stringa costituita dagli elementi di value delimitati dalla stringa separator.

-oppure-

Empty se values ha zero elementi.

Eccezioni

value è null.

La lunghezza della stringa risultante supera la lunghezza massima consentita (Int32.MaxValue).

Esempio

Nell'esempio seguente viene illustrato il Join metodo.

using namespace System;
String^ MakeLine( int initVal, int multVal, String^ sep )
{
   array<String^>^sArr = gcnew array<String^>(10);
   for ( int i = initVal; i < initVal + 10; i++ )
      sArr[ i - initVal ] = String::Format( "{0, -3}", i * multVal );
   return String::Join( sep, sArr );
}

int main()
{
   Console::WriteLine( MakeLine( 0, 5, ", " ) );
   Console::WriteLine( MakeLine( 1, 6, "  " ) );
   Console::WriteLine( MakeLine( 9, 9, ": " ) );
   Console::WriteLine( MakeLine( 4, 7, "< " ) );
}
// 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
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
open System

let makeLine initVal multVal (sep: string) =
    let sArr = Array.zeroCreate<string> 10 

    for i = initVal to initVal + 9 do
        sArr[i - initVal] <- String.Format("{0,-3}", i * multVal)

    String.Join(sep, sArr)

printfn $"""{makeLine 0 5 ", "}"""
printfn $"""{makeLine 1 6 "  "}"""
printfn $"""{makeLine 9 9 ": "}"""
printfn $"""{makeLine 4 7 "< "}"""

// 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
Public Class JoinTest
    
    Public Shared Sub Main()
        
        Console.WriteLine(MakeLine(0, 5, ", "))
        Console.WriteLine(MakeLine(1, 6, "  "))
        Console.WriteLine(MakeLine(9, 9, ": "))
        Console.WriteLine(MakeLine(4, 7, "< "))
    End Sub
    
    
    Private Shared Function MakeLine(initVal As Integer, multVal As Integer, sep As String) As String
        Dim sArr(10) As String
        Dim i As Integer
        
        
        For i = initVal To (initVal + 10) - 1
            sArr((i - initVal)) = [String].Format("{0,-3}", i * multVal)
        
        Next i
        Return [String].Join(sep, sArr)
    End Function 'MakeLine
End Class
' 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

Commenti

Ad esempio, se separator è ", " e gli elementi di value sono "mela", "arancione", "uva" e "pera", Join(separator, value) restituisce "mela, arancia, uva, pera".

Se separator è null, viene invece usata una stringa vuota (String.Empty). Se un elemento in value è null, viene utilizzata invece una stringa vuota.

Vedi anche

Si applica a

Join(Char, String[], Int32, Int32)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Concatena una matrice di stringhe, usando il separatore specificato tra ogni membro, a partire dall'elemento in value presente nella posizione di startIndex e concatenando fino a count elementi.

public:
 static System::String ^ Join(char separator, cli::array <System::String ^> ^ value, int startIndex, int count);
public static string Join (char separator, string?[] value, int startIndex, int count);
public static string Join (char separator, string[] value, int startIndex, int count);
static member Join : char * string[] * int * int -> string
Public Shared Function Join (separator As Char, value As String(), startIndex As Integer, count As Integer) As String

Parametri

separator
Char

Concatena una matrice di stringhe, usando il separatore specificato tra ogni membro, a partire dall'elemento presente in corrispondenza dell'indice specificato e includendo un numero specificato di elementi.

value
String[]

Matrice di stringhe da concatenare.

startIndex
Int32

Primo elemento in value da concatenare.

count
Int32

Numero di elementi da value da concatenare, a partire dall'elemento nella posizione di startIndex.

Restituisce

Stringa costituita da count elementi di value a partire da startIndex delimitati dal separator carattere .

-oppure-

Empty se count è zero.

Eccezioni

value è null.

startIndex o count è un valore negativo.

-oppure-

startIndex è maggiore della lunghezza di value - count.

La lunghezza della stringa risultante supera la lunghezza massima consentita (Int32.MaxValue).

Si applica a

Join(String, String[], Int32, Int32)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Concatena gli elementi specificati di una matrice di stringhe, usando tra gli elementi il separatore specificato.

public:
 static System::String ^ Join(System::String ^ separator, cli::array <System::String ^> ^ value, int startIndex, int count);
public static string Join (string separator, string[] value, int startIndex, int count);
public static string Join (string? separator, string?[] value, int startIndex, int count);
static member Join : string * string[] * int * int -> string
Public Shared Function Join (separator As String, value As String(), startIndex As Integer, count As Integer) As String

Parametri

separator
String

Stringa da usare come separatore. separator è incluso solo nella stringa restituita solo se value presenta più di un elemento.

value
String[]

Matrice contenente gli elementi da concatenare.

startIndex
Int32

Primo elemento di value da usare.

count
Int32

Numero di elementi del parametro value da usare.

Restituisce

Stringa costituita count da elementi che value iniziano a startIndex delimitati dal separator carattere.

-oppure-

Empty se count è zero.

Eccezioni

value è null.

startIndex o count è minore di 0.

-oppure-

La somma di startIndex e count è maggiore del numero di elementi in value.

Memoria insufficiente.

Esempio

Nell'esempio seguente vengono concatenati due elementi da una matrice di nomi di frutta.

// Sample for String::Join(String, String[], int int)
using namespace System;
int main()
{
   array<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'
*/
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'
open System

let vals = [| "apple"; "orange"; "grape"; "pear" |]
let sep   = ", "

printfn $"sep = '{sep}'"
printfn $"vals[] = {{'{vals[0]}' '{vals[1]}' '{vals[2]}' '{vals[3]}'}}"
let result = String.Join(sep, vals, 1, 2)
printfn $"String.Join(sep, vals, 1, 2) = '{result}'"

// This example produces the following results:
// sep = ', '
// vals[] = {'apple' 'orange' 'grape' 'pear'}
// String.Join(sep, vals, 1, 2) = 'orange, grape'
Class Sample
   Public Shared Sub Main()
      Dim val As [String]() =  {"apple", "orange", "grape", "pear"}
      Dim sep As [String] = ", "
      Dim result As [String]
      
      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)
   End Sub
End Class 
'This example displays the following output:
'       sep = ', '
'       val() = {'apple' 'orange' 'grape' 'pear'}
'       String.Join(sep, val, 1, 2) = 'orange, grape'

Commenti

Ad esempio, se separator è ", " e gli elementi di value sono "mela", "arancione", "uva" e "pera", Join(separator, value, 1, 2) restituisce "arancione, uva".

Se separator è null, viene usata invece una stringa vuota (String.Empty). Se un elemento in value è null, viene invece usata una stringa vuota.

Vedi anche

Si applica a

Join<T>(Char, IEnumerable<T>)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Concatena i membri di una raccolta, usando tra i membri il separatore specificato.

public:
generic <typename T>
 static System::String ^ Join(char separator, System::Collections::Generic::IEnumerable<T> ^ values);
public static string Join<T> (char separator, System.Collections.Generic.IEnumerable<T> values);
static member Join : char * seq<'T> -> string
Public Shared Function Join(Of T) (separator As Char, values As IEnumerable(Of T)) As String

Parametri di tipo

T

Tipo dei membri di values.

Parametri

separator
Char

Carattere da usare come separatore. separator è incluso solo nella stringa restituita solo se values presenta più di un elemento.

values
IEnumerable<T>

Raccolta che contiene gli oggetti da concatenare.

Restituisce

Stringa costituita dai membri di values delimitati dal carattere separator.

-oppure-

Empty se values non ha elementi.

Eccezioni

values è null.

La lunghezza della stringa risultante supera la lunghezza massima consentita (Int32.MaxValue).

Si applica a

Join<T>(String, IEnumerable<T>)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

Concatena i membri di una raccolta, usando tra i membri il separatore specificato.

public:
generic <typename T>
 static System::String ^ Join(System::String ^ separator, System::Collections::Generic::IEnumerable<T> ^ values);
public static string Join<T> (string separator, System.Collections.Generic.IEnumerable<T> values);
public static string Join<T> (string? separator, System.Collections.Generic.IEnumerable<T> values);
[System.Runtime.InteropServices.ComVisible(false)]
public static string Join<T> (string separator, System.Collections.Generic.IEnumerable<T> values);
static member Join : string * seq<'T> -> string
[<System.Runtime.InteropServices.ComVisible(false)>]
static member Join : string * seq<'T> -> string
Public Shared Function Join(Of T) (separator As String, values As IEnumerable(Of T)) As String

Parametri di tipo

T

Tipo dei membri di values.

Parametri

separator
String

Stringa da usare come separatore. separator è incluso solo nella stringa restituita solo se values presenta più di un elemento.

values
IEnumerable<T>

Raccolta che contiene gli oggetti da concatenare.

Restituisce

Stringa costituita dagli elementi di values delimitati dalla stringa separator.

-oppure-

Empty se values non ha elementi.

Attributi

Eccezioni

values è null.

La lunghezza della stringa risultante supera la lunghezza massima consentita (Int32.MaxValue).

Esempio

Nell'esempio seguente viene usato l'algoritmo Sieve di Eratosthenes per calcolare i numeri primi minori o uguali a 100. Assegna il risultato a un List<T> oggetto di tipo integer, che passa quindi al Join<T>(String, IEnumerable<T>) metodo .

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
open System

let getPrimes maxPrime =
    let values = Array.CreateInstance(typeof<int>, [| maxPrime - 1 |], [| 2 |])
    // Use Sieve of Eratosthenes to determine prime numbers.
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 |> float |> sqrt |> ceil |> int do
        if values.GetValue i <> 1 then
            for multiplier = i to maxPrime / 2 do
                if i * multiplier <= maxPrime then
                    values.SetValue(1, i * multiplier)

    let primes = ResizeArray()
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
        if values.GetValue i :?> int = 0 then
            primes.Add i
    primes

let maxPrime = 100
let primes = getPrimes maxPrime
printfn $"Primes less than {maxPrime}:"
printfn $"""   {String.Join(" ", 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
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim maxPrime As Integer = 100
      Dim primes As List(Of Integer) = GetPrimes(maxPrime)
      Console.WriteLine("Primes less than {0}:", maxPrime)
      Console.WriteLine("   {0}", String.Join(" ", primes))
   End Sub
   
   Private Function GetPrimes(maxPrime As Integer) As List(Of Integer)
      Dim values As Array = Array.CreateInstance(GetType(Integer), _
                              New Integer() { maxPrime - 1}, New Integer(){ 2 }) 
        ' Use Sieve of Eratosthenes to determine prime numbers.
      For ctr As Integer = values.GetLowerBound(0) To _
                           CInt(Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))))
         If CInt(values.GetValue(ctr)) = 1 Then Continue For
         
         For multiplier As Integer = ctr To maxPrime \ 2
            If ctr * multiplier <= maxPrime Then values.SetValue(1, ctr * multiplier)
         Next   
      Next      
      
      Dim primes As New System.Collections.Generic.List(Of Integer)
      For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0)
         If CInt(values.GetValue(ctr)) = 0 Then primes.Add(ctr)
      Next            
      Return primes
   End Function   
End Module
' 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

Commenti

Se separator è null, viene usata invece una stringa vuota (String.Empty). Se un membro di values è null, viene invece usata una stringa vuota.

Join<T>(String, IEnumerable<T>) è un metodo pratico che consente di concatenare ogni membro di una IEnumerable<T> raccolta senza prima convertirli in stringhe. La rappresentazione stringa di ogni oggetto nell'insieme IEnumerable<T> è derivata chiamando il metodo dell'oggetto ToString .

Questo metodo è particolarmente utile con le espressioni di query LINQ (Query) Language-Integrated. Ad esempio, il codice seguente definisce una classe molto semplice Animal che contiene il nome di un animale e l'ordine a cui appartiene. Definisce quindi un List<T> oggetto contenente un numero di Animal oggetti. Il Enumerable.Where metodo di estensione viene chiamato per estrarre gli oggetti la Animal cui Order proprietà è uguale a "Roditori". Il risultato viene passato al Join<T>(String, IEnumerable<T>) metodo .

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
// This example uses F#'s Seq.filter function instead of Linq.
open System

type Animal =
  { Kind: string
    Order: string }
    override this.ToString() =
        this.Kind

let animals = ResizeArray()
animals.Add { Kind = "Squirrel"; Order = "Rodent" }
animals.Add { Kind = "Gray Wolf"; Order = "Carnivora" }
animals.Add { Kind = "Capybara"; Order = "Rodent" }
String.Join(" ", animals |> Seq.filter (fun animal -> animal.Order = "Rodent"))
|> printfn "%s"
// The example displays the following output:
//      Squirrel Capybara
Imports System.Collections.Generic

Public Class Animal
   Public Kind As String
   Public Order As String
   
   Public Sub New(kind As String, order As String)
      Me.Kind = kind
      Me.Order = order
   End Sub
   
   Public Overrides Function ToString() As String
      Return Me.Kind
   End Function
End Class

Module Example
   Public Sub Main()
      Dim animals As New List(Of Animal)
      animals.Add(New Animal("Squirrel", "Rodent"))
      animals.Add(New Animal("Gray Wolf", "Carnivora"))
      animals.Add(New Animal("Capybara", "Rodent")) 
      Dim output As String = String.Join(" ", animals.Where(Function(animal) _
                                           animal.Order = "Rodent"))
      Console.WriteLine(output)                                           
   End Sub
End Module
' The example displays the following output:
'      Squirrel Capybara

Vedi anche

Si applica a