char Lookup Table
This page was last reviewed on Aug 10, 2023.
Dot Net Perls
Char lookup table. Character transformations can be slow. We can have elaborate logic in them. With a lookup table, we can instantly map characters.
For ASCII chars, like ABC, we can use a small lookup table of 128 chars. Then we can use char values (like "A") as the index, and store chars in each slot.
Example code. Let us begin with this simple example. We use a char table of 128 elements to store the result of toUpperCase. We store uppercased versions of all chars.
Then We can transform chars with a simple table lookup. No call to Character.toUpperCase is needed.
public class Program { static char[] table = new char[128]; public static void main(String[] args) { // Set up the lookup table. for (int i = 0; i < 128; i++) { // Get character for this int. char c = (char) i; // Convert to uppercase. char result = Character.toUpperCase(c); // Store in lookup table field. table[c] = result; } // Loop over string characters. String name = "Carrot123"; for (int i = 0; i < name.length(); i++) { // Get char from lookup table based on string char. char result = table[name.charAt(i)]; // Write results. System.out.println(name.charAt(i) + "/" + result); } } }
C/C a/A r/R r/R o/O t/T 1/1 2/2 3/3
Some performance notes. Character lookup tables are an optimization in many programs. They help the most on slow operations—toUpperCase is too fast to show much benefit from a table.
For a cipher, like ROT13 or a Caesar cipher, a char lookup table can show more improvement. And lookup tables (a form of memoization) are excellent for mathematical computations as well.
Caesar Cipher
Some limitations, summary. Char lookup tables must accommodate all characters, or use a range check for values. This ensures no exceptions are thrown.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.