首頁  >  文章  >  後端開發  >  C# 中的字串文字與字串對象

C# 中的字串文字與字串對象

WBOY
WBOY轉載
2023-09-06 17:45:07761瀏覽

C# 中的字符串文字与字符串对象

字串文字

字串文字或常數用雙引號「」或@「」括起來。字串包含與字元文字類似的字元:純字元、轉義序列和通用字元。

以下是字串文字的一些範例-

Hello, World"
"Welcome, \

以下是顯示字串文字用法的範例-

範例

using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {

         // string
         string str1 ="Hello, World";
         Console.WriteLine(str1);

         // Multi-line string
         string str2 = @"Welcome,
         Hope you are doing great!";

         Console.WriteLine(str2);
      }
   }
}

字串物件

使用以下方法之一建立字串物件-

  • 透過將字串文字指派給字串變數
  • 透過使用String 類別建構子
  • 透過使用字串連接運算子( )
  • 透過檢索屬性或呼叫傳回字串的方法
  • 透過呼叫格式化方法將值或物件轉換為其字串表示形式

以下是如何建立字串物件並比較兩個字串-

範例

using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {
         string str1 = "John";
         string str2 = "Andy";

         if (String.Compare(str1, str2) == 0) {
            Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
         } else {
            Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
         }
         Console.ReadKey() ;
      }
   }
}

以上是C# 中的字串文字與字串對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除