C# String Join()

Join() 方法使用指定的连接符连接数组的元素。

示例

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
   
      // creates a string array.
      string[] text = { "C#", "Java", "C++" };
        
// joins string with space between them Console.WriteLine(String.Join(" ", text));
Console.ReadLine(); } } } // Output: C# Java C++

Join() 语法

字符串 Join() 方法的语法是

String.Join(String separator, String[] value, Int32 startIndex, Int32 count)

这里,Join()String 类的其中一个方法。


Join() 参数

Join() 方法接受以下参数

  • separator - 用于连接元素的连接符
  • value - 要连接的字符串数组
  • startIndex - value 中要连接的第一个元素
  • count - 要连接的元素数量(从 startIndex 开始)

Join() 返回值

  • 返回一个由连接符分隔的元素组成的字符串

示例 1:C# String Join()

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
   
      // creates a string array.
      string[] text = {"C#", "Java", "C++"};
        
// joins string with "/" between them string result = String.Join("/", text);
Console.WriteLine(result); Console.ReadLine(); } } }

输出

C#/Java/C++

这里,text 中的元素 "C#""Java""C++" 使用 / 连接符连接到 Join()


示例 2:带起始索引和计数的 Join()

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
   
      // Creating a string array
      string[] text = {"C#", "Java", "C++", "Swift", "Go"};

// joins 2 strings from index 1 string s1 = String.Join("-", text, 1, 2);
Console.WriteLine(s1); Console.ReadLine(); } } }

输出

Java-C++

在上面的示例中,请注意这一行:

string s1 = String.Join("-", text, 1, 2);

这里,

  • 1 - 要连接的文本的起始索引("Java" 的索引)
  • 2 - 要连接的元素数量
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战