String Literals (Hằng chuỗi)
String literal/hằng chuỗi đóng trong ngoặc kép "" hoặc @"". Chứa ký tự thường, escape sequence, universal character.
Ví dụ:
"Hello, World" @"Welcome, Hope you are doing great!"
Ví dụ
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string str1 = "Hello, World";
Console.WriteLine(str1);
// Chuỗi nhiều dòng
string str2 = @"Welcome,
Hope you are doing great!";
Console.WriteLine(str2);
}
}
}
String Object (Đối tượng chuỗi)
Tạo string object bằng:
- Gán string literal cho biến String
- Dùng constructor String class
- Dùng toán tử nối
+ - Lấy property hoặc gọi method trả về string
- Gọi phương thức format chuyển đổi giá trị/object thành string
Ví dụ tạo object và so sánh 2 chuỗi:
Ví dụ
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 + " và " + str2 + " là chuỗi bằng nhau.");
} else {
Console.WriteLine(str1 + " và " + str2 + " không phải chuỗi bằng nhau.");
}
Console.ReadKey();
}
}
}