C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: We can parse a string containing digits and immediately use math on these values. This can speed up some programs.
int.ParseC# program that converts ASCII digits
using System;
class Program
{
static void Main()
{
// Convert char values to equivalent ints.
string values = "1234";
for (int i = 0; i < values.Length; i++)
{
int convertedDigit = values[i] - 48;
Console.WriteLine($"Char: {values[i]}; Digit: {convertedDigit}");
}
}
}
Output
Char: 1; Digit: 1
Char: 2; Digit: 2
Char: 3; Digit: 3
Char: 4; Digit: 4
So: We can add 32 to go from uppercase to lower. This might seem the opposite of what is logical.
C# program that lowercases chars in ASCII
using System;
class Program
{
static void Main()
{
// Convert uppercase values to lowercase.
string values = "ABCD";
for (int i = 0; i < values.Length; i++)
{
char convertedChar = (char)(values[i] + 32);
Console.WriteLine($"Uppercase: {values[i]}; Lowercase: {convertedChar}");
}
}
}
Output
Uppercase: A; Lowercase: a
Uppercase: B; Lowercase: b
Uppercase: C; Lowercase: c
Uppercase: D; Lowercase: d
Here: We subtract 97 to go from a letter to an index. The lowercase letter "b" for example is now the value 1.
C# program that converts letters to indexes
using System;
class Program
{
static void Main()
{
// Convert lowercase letters to indexes.
string values = "abcd";
for (int i = 0; i < values.Length; i++)
{
int convertedIndex = values[i] - 97;
Console.WriteLine($"Letter: {values[i]}; Index: {convertedIndex}");
}
}
}
Output
Letter: a; Index: 0
Letter: b; Index: 1
Letter: c; Index: 2
Letter: d; Index: 3