C# String Length

The Length property in C# is used to find the number of characters in a string. This property is useful when you need to know how many characters are in a string or when you want to loop through its characters.

Key Topics

1. The Length Property

Example: Getting String Length

string message = "Hello, World!";
int length = message.Length;
Console.WriteLine($"The length of the string is: {length}");

Output:

The length of the string is: 13

2. Using Length in Loops

You can use the Length property to iterate over each character in a string.

Example: Iterating Over a String Using Length

string word = "Hello";
for(int i = 0; i < word.Length; i++)
{
    Console.WriteLine($"Character at index {i}: {word[i]}");
}

Output:

Character at index 0: H Character at index 1: e Character at index 2: l Character at index 3: l Character at index 4: o

3. Length vs. Count

While the Length property is used for arrays and strings, the Count property is used for collections like lists.

Example: Difference Between Length and Count

string[] words = { "apple", "banana", "cherry" };
Console.WriteLine(words.Length);  // Outputs: 3

List<string> wordList = new List<string>(words);
Console.WriteLine(wordList.Count); // Outputs: 3

Key Takeaways

  • The Length property returns the total number of characters in a string.
  • It is commonly used in loops to iterate over each character.
  • For collections like lists, use Count instead of Length.