ในการสร้างวัตถุสตริงใน C # ให้ใช้วิธีใดวิธีหนึ่งด้านล่าง
- โดยการกำหนดตัวอักษรสตริงให้กับตัวแปรสตริง
- โดยใช้ตัวสร้างคลาสสตริง
- โดยใช้ตัวดำเนินการเชื่อมสตริง (+)
- โดยการเรียกคุณสมบัติหรือเรียกวิธีการที่ส่งคืนสตริง
- โดยการเรียกวิธีการจัดรูปแบบเพื่อแปลงค่าหรือวัตถุเป็นการแสดงสตริง
ต่อไปนี้คือตัวอย่างที่แสดงวิธีต่างๆ ในการสร้างวัตถุสตริงใน C#
ตัวอย่าง
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
//from string literal and string concatenation
string fname, lname;
fname = "Brad ";
lname = "Pitt";
char []letters= { 'W', 'e', 'b'};
string [] sarray={ "Web", "World"};
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
//by using string constructor { 'W, 'e', 'b'};
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
//methods returning string { "Web", "World" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
//formatting method to convert a value
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}", waiting);
Console.WriteLine("Message: {0}", chat);
}
}
} ผลลัพธ์
Full Name: Brad Pitt Greetings: Web Message: Web World Message: Message sent at 5:58 PM on Wednesday, October 10, 2012