27 votes

C# : string[] vers string délimité. Existe-t-il une solution simple ?

Ce que je préférerais, c'est quelque chose comme :

string[] strArray = {"Hi", "how", "are", "you"};
string strNew = strArray.Delimit(chDelimiter);

Or, cette fonction n'existe pas. J'ai parcouru le MSDN et rien ne m'a semblé être une fonction capable d'effectuer la même action. J'ai regardé StringBuilder, et là encore, rien ne m'a sauté aux yeux. J'aimerais savoir si quelqu'un connaît une fonction pas trop compliquée pour faire d'un tableau une chaîne de caractères délimitée. Merci pour votre aide.

UPDATE : Wow, lol, my bad. Je n'arrêtais pas de regarder le .Join sur le tableau lui-même et ça m'énervait. Je n'ai même pas regardé String.Join. Merci les gars. Une fois qu'il me permettra d'accepter, je le ferai. Merci pour votre aide.

52voto

kbrimington Points 14081

Pour les tableaux, vous pouvez utiliser :

string.Join(", ", strArray);

Personnellement, j'utilise une méthode d'extension que je peux appliquer aux collections énumérables de tous types :

public static string Flatten(this IEnumerable elems, string separator)
{
    if (elems == null)
    {
        return null;
    }

    StringBuilder sb = new StringBuilder();
    foreach (object elem in elems)
    {
        if (sb.Length > 0)
        {
            sb.Append(separator);
        }

        sb.Append(elem);
    }

    return sb.ToString();
}

...Que j'utilise comme suit :

strArray.Flatten(", ");

7voto

David Hoerster Points 18815

Vous pouvez utiliser l'option statique String.Join méthode :

String strNew = String.Join(chDelimiter, strArray);


EDIT : En réponse au commentaire : D'après votre commentaire, vous pouvez prendre plusieurs tableaux, les concaténer, puis joindre l'ensemble du tableau résultant. Vous pouvez le faire en utilisant la méthode d'extension IEnumerable Concat . Voici un exemple :

//define my two arrays...
string[] strArray = { "Hi", "how", "are", "you" };
string[] strArray2 = { "Hola", "como", "esta", "usted" };

//Concatenate the two arrays together (forming a third array) and then call join on it...
string strNew = String.Join(",", strArray.Concat(strArray2));

J'espère que cela vous aidera !

5voto

Incognito Points 10148

Jetez un coup d'œil sur String.Join() .

Votre échantillon doit ressembler à ceci :

        string delimiter = ","
        string[] strArray = { "Hi", "how", "are", "you" };
        string strNew = String.Join(delimiter, strArray);

4voto

Jim Schubert Points 10234

Utilice String.Join

string[] strArray = {"Hi", "how", "are", "you"};
string strNew = String.Join("," strArray);

1voto

theburningmonk Points 5590

Dans ce cas, String.Join() est probablement la solution la plus simple, mais vous pouvez également utiliser LINQ

var comSeparatedStrings = strings.Aggregate((acc, item) => acc + ", " + item);

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X