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);
      }
   }
}

字串物件

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

  • 將字串字面量賦值給字串變數
  • 使用字串類建構函式
  • 使用字串連線運算子 +
  • 透過檢索屬性或呼叫返回字串的方法
  • 透過呼叫一個格式化方法,將一個值或物件轉換成它的字串表示

以下是如何建立一個字串物件和比較兩個字串 −

示例

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() ;
      }
   }
}

更新於:2020-06-21

1 千+ 閱讀量

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.