如何在C#中建立一個字串物件?


要建立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

更新於: 23-Jun-2020

4K+ 次瀏覽

開啟你的 職業生涯

完成本課程以獲得認證

開始學習
廣告
© . All rights reserved.