string.Length / IndexOf()
The Length property returns the length of a string, and the IndexOf() method returns the position where a specified character or string first appears.
Syntax
// Returns the length (number of characters) of a string. string.Length // Returns the index of the first occurrence of the specified value. Returns -1 if not found. string.IndexOf(string value) string.IndexOf(string value, int startIndex) // Returns the index of the last occurrence of the specified value. Returns -1 if not found. string.LastIndexOf(string value)
Member List
| Member | Description |
|---|---|
| Length | Returns the number of characters in the string as an integer. Returns 0 for an empty string. |
| IndexOf(string value) | Returns the zero-based index of the first occurrence of the specified string. Returns -1 if not found. |
| IndexOf(string value, int startIndex) | Searches starting at the specified startIndex and returns the index of the first occurrence found. |
| LastIndexOf(string value) | Returns the index of the last occurrence of the specified string. Returns -1 if not found. |
Sample Code
using System;
string greeting = "Hello, World!";
// Use Length to get the character count.
Console.WriteLine(greeting.Length); // 13
// Use IndexOf() to find the position of a substring.
int pos = greeting.IndexOf("World");
Console.WriteLine(pos); // 7
// Returns -1 if the substring is not found.
int notFound = greeting.IndexOf("xyz");
Console.WriteLine(notFound); // -1
// Use startIndex to search from a specific position.
string path = "C:/users/akiba/documents/akiba.txt";
int first = path.IndexOf("akiba");
int next = path.IndexOf("akiba", first + 1);
Console.WriteLine(first); // 8
Console.WriteLine(next); // 25
// Use LastIndexOf() to find the last occurrence.
string text = "abcabcabc";
Console.WriteLine(text.LastIndexOf("a")); // 6
Notes
Length is a property of the string (not a method), so no parentheses are needed when accessing it. In C#, string indices are zero-based, and each character — including multi-byte characters — counts as one.
IndexOf() is case-sensitive. To perform a case-insensitive search, use IndexOf(value, StringComparison.OrdinalIgnoreCase).
To extract or remove part of a string, see Substring() / Remove(). To replace characters or check for containment, see Replace() / Contains().
If you find any errors or copyright issues, please contact us.