C# String.Join 方法

using System;

class Program
{
    static void Main()
    {
        string[] arr = { "one", "two", "three" };

        // "string" can be lowercase.
        Console.WriteLine(string.Join(",", arr));

        // ... "String" can be uppercase.
        Console.WriteLine(String.Join(",", arr));
    }
}

Output

one,two,three
one,two,three

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string[] catSpecies = { "Aegean", "Birman", "Main Coon", "Nebulung" };
        Console.WriteLine(CombineA(catSpecies));
        Console.WriteLine(CombineB(catSpecies));
    }

    /// <summary>
    /// Combine strings with commas.
    /// </summary>
    static string CombineA(string[] arr)
    {
        return string.Join(",", arr);
    }

    /// <summary>
    /// Combine strings with commas.
    /// </summary>
    static string CombineB(string[] arr)
    {
        StringBuilder builder = new StringBuilder();
        foreach (string s in arr)
        {
            builder.Append(s).Append(",");
        }
        return builder.ToString().TrimEnd(new char[] { ',' });
    }
}

Output

Aegean,Birman,Main Coon,Nebulung
Aegean,Birman,Main Coon,Nebulung

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a List of three strings.
        var list = new List<string>() { "cat", "dog", "rat" };
        // Join the strings from the List.
        string joined = string.Join<string>("*", list);
        // Display.
        Console.WriteLine(joined);
    }
}

Output

cat*dog*rat

static string CombineA(string[] arr)
{
    return string.Join(",", arr);
}

static string CombineB(string[] arr)
{
    var builder = new System.Text.StringBuilder();
    foreach (string s in arr)
    {
        builder.Append(s).Append(",");
    }
    return builder.ToString(); // Has ending comma [difference]
}

Results

string.Join:                 157 ms [faster]
StringBuilder Append method: 270 ms

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值