C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: This is because the final offset in a string is always one less than its length, when length is one or more.
String LengthConsole: With Console, we print some text and the character values to the terminal window.
ConsoleInfo: You can pass a char directly to Console.WriteLine because WriteLine provides an overloaded method with an appropriate signature.
OverloadC# program that gets individual chars
using System;
class Program
{
static void Main()
{
// Get values from this string.
string value = "The Dev Codes";
char first = value[0];
char second = value[1];
char last = value[value.Length - 1];
// Write chars.
Console.WriteLine("--- 'The Dev Codes' ---");
Console.Write("First char: ");
Console.WriteLine(first);
Console.Write("Second char: ");
Console.WriteLine(second);
Console.Write("Last char: ");
Console.WriteLine(last);
}
}
Output
--- 'The Dev Codes' ---
First char: D
Second char: o
Last char: s
And: With empty strings, the Length is zero, so there are no available offsets for you to access in the string.
Here: The string.IsNullOrEmpty static method checks for strings that cannot have their characters accessed.
IsNullOrEmpty, IsNullOrWhiteSpaceStaticTip: IsNullOrEmpty allows the enclosed block to execute only when there is one or more characters.
C# program that gets chars from different strings
using System;
class Program
{
static void Main()
{
// Array of string values.
string[] values = { "The Dev Codes", "D", "", "Sam" };
// Loop over string values.
foreach (string value in values)
{
// Display the string.
Console.WriteLine("--- '{0}' ---", value);
// We can't get chars from null or empty strings.
if (!string.IsNullOrEmpty(value))
{
char first = value[0];
char last = value[value.Length - 1];
Console.Write("First char: ");
Console.WriteLine(first);
Console.Write("Last char: ");
Console.WriteLine(last);
}
}
}
}
Output
--- 'The Dev Codes' ---
First char: D
Last char: s
--- 'D' ---
First char: D
Last char: D
--- '' ---
--- 'Sam' ---
First char: S
Last char: m
And: In the .NET Framework, the chars are accessed in an internal method, not in managed code.
Char indexer:
.property instance char Chars
{
.get instance char System.String::get_Chars(int32)
}
Info: I changed an important algorithm to use the char indexer instead of 1-character substrings. The program became 75% faster.
Levenshtein