Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีการต่อสตริงใน C# ด้วย String.Concat() พร้อมตัวอย่าง

ใน C# สามารถต่อสตริง (Concatenate Strings) ได้หลายวิธี แต่หนึ่งในวิธีมาตรฐานและใช้งานง่ายคือการใช้เมธอด String.Concat() เมธอดนี้จะรวมสตริงหลายตัวเข้าด้วยกันเป็นสตริงเดียว โดยไม่เปลี่ยนแปลงค่าต้นฉบับ

รูปแบบไวยากรณ์ (Syntax)

public static string Concat(string str1, string str2);

พารามิเตอร์ str1 และ str2 คือสตริงที่ต้องการนำมาต่อกัน

ตัวอย่างที่ 1: การต่อสตริง 2 ตัว

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        string str1 = "Jack";
        string str2 = "Sparrow";

        Console.WriteLine("String 1 = " + str1);
        Console.WriteLine("HashCode of String 1 = " + str1.GetHashCode());
        Console.WriteLine("Does String1 begin with 'E'? = " + str1.StartsWith("E"));
        
        Console.WriteLine("\nString 2 = " + str2);
        Console.WriteLine("HashCode of String 2 = " + str2.GetHashCode());
        Console.WriteLine("Does String2 begin with 'E'? = " + str2.StartsWith("E"));
        
        Console.WriteLine("\nString 1 equals String 2? = {0}", str1.Equals(str2));
        Console.WriteLine("Concatenation Result = " + String.Concat(str1, str2));
    }
}

ผลลัพธ์

String 1 = Jack
HashCode of String 1 = 1167841345
Does String1 begin with E? = False

String 2 = Sparrow
HashCode of String 2 = -359606417
Does String2 begin with E? = False

String 1 is equal to String 2? = False
Concatenation Result = JackSparrow

ตัวอย่างที่ 2: การต่อสตริงจากอาร์เรย์ (params string[])

เมธอด Concat() ยังรองรับการรับพารามิเตอร์เป็นอาร์เรย์สตริงได้อีกด้วย

รูปแบบไวยากรณ์

public static string Concat(params string[] arr);

arr คืออาร์เรย์ของสตริงที่ต้องการนำมาต่อกัน

โค้ดตัวอย่าง

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        string[] strArr = { "This", "is", "it", "!" };
        
        Console.WriteLine("String Array...");
        foreach (string s in strArr)
        {
            Console.WriteLine(s);
        }
        
        Console.WriteLine("Concatenation = {0}", string.Concat(strArr));
        
        // เปรียบเทียบกับ String.Join() ที่สามารถใส่ตัวคั่นได้
        string str = string.Join("/", strArr);
        Console.WriteLine("Result (after joining) = " + str);
    }
}

ผลลัพธ์

String Array...
This
is
it
!
Concatenation = Thisisit!
Result (after joining) = This/is/it/!

สรุป

  • String.Concat() ใช้สำหรับต่อสตริงโดยไม่มีตัวคั่น
  • รองรับทั้งการส่งสตริงแต่ละตัวและส่งเป็นอาร์เรย์
  • หากต้องการต่อสตริงพร้อมตัวคั่น (เช่น คอมมา, ขีดกลาง) ให้ใช้ String.Join() แทน
  • สำหรับการต่อสตริงจำนวนมากในลูป แนะนำให้ใช้ StringBuilder เพื่อประสิทธิภาพที่ดีกว่า