Characters Inside Strings
Each string is a sequence of characters, where each character is defined by a code number. For example, the string “ABC 123” is stored as a sequence of numbers: 65 65 66 67 32 49 50 51 66 49 50 51. These numbers are called ASCII codes. ASCII stands for American Standard Code for Information Exchange.
- Open the ASCII chart at this link.
- Find the Dec ASCII codes for upper-case A, B, and Z.
- Find the Dec ASCII codes for lower-case a through z.
- Find the Dec ASCII codes for digits.
You can use Makecode blocks to return the ASCII code of a character, and also to return the character for a given ASCII code. Let’s try that!
Example project: chars_in_strings_intro
- Enter and name chars_in_strings_intro.
- Click the Download button.
- Check the results in the serial terminal.
- Verify that it displays a message that the ASCII code for A is 65, and the character with the ASCII code 66 is B.
- Try some of your own characters and ASCII codes.
How chars_in_strings_intro Works
The block serial write line (“n = ASCII code for A”) displays a heading to help give context to the messages below it.
The block char code from (“ ”) at () returns the ASCII code of a string that contains a single character. The ASCII code for the character A is 65. So, char code from (“A”) at (0) returns 65, and n = char code from (“A”) at (0) stores the value 65 in the variable n.
After that, serial write line (join(“n = “)(n)) displays “n =”, followed by the value of n, which is 65. Lastly, the serial new line just prints an empty line.
After that empty line, serial write line (“c = character with ASCII code 66”) prints another heading.
The text from char code () block accepts an ASCII code, and returns that ASCII code’s character. So, c = text from char code (66) stores the character B in a variable named c.
Since c now stores the character B, serial write line (“c =”, c) prints c = B.