การหาความยาวสตริงใน C#
ใน C# คุณสามารถหาความยาวของสตริงได้โดยใช้คุณสมบัติ Length ของคลาส string คุณสมบัตินี้คืนค่าจำนวนตัวอักษร (char) ในสตริงเป็นจำนวนเต็ม
ไวยากรณ์
int length = str.Length;
ตัวอย่างโค้ดสมบูรณ์
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
string str = "Amit";
Console.WriteLine("สตริง: " + str);
Console.WriteLine("ความยาวสตริง: " + str.Length);
Console.ReadKey();
}
}
}
ผลลัพธ์
สตริง: Amit
ความยาวสตริง: 4
รายละเอียดเพิ่มเติม
Lengthนับจำนวนchar(16-bit Unicode code units) ไม่ใช่จำนวน grapheme clusters หรือ code points- สตริงว่าง (
"") มีความยาว 0 - สตริงที่เป็น
nullจะโยนNullReferenceExceptionหากเข้าถึง.Length - สำหรับสตริงที่มีตัวอักษรพิเศษ (เช่น emoji) อาจต้องใช้
StringInfo.LengthInTextElementsเพื่อนับที่เห็นจริง
ตัวอย่างการป้องกัน null
string str = null;
int length = str?.Length ?? 0; // ใช้ null-conditional และ null-coalescing operator
Console.WriteLine(length); // 0