Export (0) Print
Expand All

String.Length Property

Gets the number of characters in this instance.

[Visual Basic]
Public ReadOnly Property Length As Integer
[C#]
public int Length {get;}
[C++]
public: __property int get_Length();
[JScript]
public function get Length() : int;

Property Value

The number of characters in this instance.

Remarks

The Length property returns the number of Char objects in this instance, not the number of Unicode characters. The reason is that a Unicode character might be represented by more than one Char. Use the System.Globalization.StringInfo class to work with each Unicode character instead of each Char.

Example

[Visual Basic, C#, C++] The following example demonstrates the Length property.

[Visual Basic] 
' Sample for String.Length
Imports System

Class Sample
   Public Shared Sub Main()
      Dim str As String = "abcdefg"
      Console.WriteLine("1) The length of '{0}' is {1}", str, str.Length)
      Console.WriteLine("2) The length of '{0}' is {1}", "xyz", "xyz".Length)
   End Sub 'Main
End Class 'Sample
'
'This example produces the following results:
'1) The length of 'abcdefg' is 7
'2) The length of 'xyz' is 3
'

[C#] 
// Sample for String.Length
using System;

class Sample 
{
    public static void Main() 
    {
    string str = "abcdefg";
    Console.WriteLine("1) The length of '{0}' is {1}", str, str.Length);
    Console.WriteLine("2) The length of '{0}' is {1}", "xyz", "xyz".Length);
    }
}
/*
This example produces the following results:
1) The length of 'abcdefg' is 7
2) The length of 'xyz' is 3
*/

[C++] 
// Sample for String::Length
#using <mscorlib.dll>

using namespace System;

int main() {
   String* str = S"abcdefg";
   Console::WriteLine(S"1) The length of '{0}' is {1}", str, __box( str->Length));
   Console::WriteLine(S"2) The length of '{0}' is {1}", S"xyz", __box( S"xyz"->Length));
}
/*
This example produces the following results:
1) The length of 'abcdefg' is 7
2) The length of 'xyz' is 3
*/

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

String Class | String Members | System Namespace | Int32

Show:
© 2014 Microsoft