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() ;
}
}
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP