Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Các thuộc tính của String trong C#

Giới thiệu

Lớp String trong C# có hai thuộc tính chính:

Thuộc tính Mô tả
Chars[int index] (indexer) Lấy ký tự tại vị trí chỉ định (chỉ đọc).
Length Số lượng ký tự (UTF-16 code units) trong chuỗi.

Ngoài ra, có các phương thức tĩnh hữu ích: IsNullOrEmpty(), IsNullOrWhiteSpace(), Compare(), Concat(), Join(), v.v.

Ví dụ 1 - Chars và Length

using System;

public class Demo
{
    public static void Main()
    {
        string str1 = "h8b9";
        string str2 = "abcdef";

        Console.WriteLine("str1 null hoặc rỗng? = " + string.IsNullOrEmpty(str1));
        Console.WriteLine("str2 null hoặc rỗng? = " + string.IsNullOrEmpty(str2));

        bool val = str1 != str2;
        Console.WriteLine("str1 khác str2? = " + val);

        for (int i = 0; i < str1.Length; i++)
        {
            if (Char.IsLetter(str1[i]))
                Console.WriteLine(str1[i] + " là chữ cái");
            else
                Console.WriteLine(str1[i] + " là số");
        }
    }
}

Kết quả

str1 null hoặc rỗng? = False
str2 null hoặc rỗng? = False
str1 khác str2? = True
h là chữ cái
8 là số
b là chữ cái
9 là số

Ví dụ 2 - Length và IsNullOrWhiteSpace

using System;

public class Demo
{
    public static void Main()
    {
        string str1 = "hijklm";
        string str2 = String.Empty;

        Console.WriteLine("str1 null hoặc whitespace? = " + String.IsNullOrWhiteSpace(str1));
        Console.WriteLine("str2 null hoặc whitespace? = " + String.IsNullOrWhiteSpace(str2));

        Console.WriteLine("Độ dài str1 = " + str1.Length);
        Console.WriteLine("Độ dài str2 = " + str2.Length); // 0
        Console.WriteLine("Độ dài chuỗi literal = " + "demo".Length); // 4
    }
}

Kết quả

str1 null hoặc whitespace? = False
str2 null hoặc whitespace? = True
Độ dài str1 = 6
Độ dài str2 = 0
Độ dài chuỗi literal = 4

Lưu ý quan trọng

  • Length trả về số UTF-16 code units, không phải số ký tự Unicode (grapheme clusters). Emoji, ký tự ghép có thể Length > 1.
  • Indexer Chars[i] chỉ đọc (string immutable).
  • IsNullOrEmpty: true nếu null hoặc Length == 0.
  • IsNullOrWhiteSpace: true nếu null, rỗng, hoặc chỉ chứa khoảng trắng (space, tab, newline...).
  • Để đếm ký tự Unicode thực sự: StringInfo.GetTextElementEnumerator() hoặc thư viện ICU.