Text types are a category of variables in programming that allow us to manipulate and work with text data, such as words, phrases, names, and messages.
These variable types are very common in our programs (for example, a person’s name, a shipping address, or the text to display to the user in a dialog window).
This is because humans use words and text to communicate. However, for a computer, handling text is not so simple and natural. So we have had to build the necessary structures to manage it.
In general, we will frequently find two types of text variables in different programming languages
- Char, for individual characters
- String, for complete strings of text
The char type
The char variable type (abbreviation for “character” in English), is the basic unit of text used in many programming languages. It represents a single character, such as a letter, a number, or a symbol.
In reality, a computer doesn’t understand anything about characters or text. They only know how to handle numbers. So, how are characters stored in a computer?
This is where the character translation table comes into play, such as ASCII or Unicode. These tables assign a unique number to each character (for example, the character “A” is represented by the number 65 in the ASCII table).
In this way, when we work with char variables in a program, we are actually manipulating the numbers that represent the characters according to a specific encoding.
The string type
While char is the basic unit of text, in most cases we need to work with longer strings of text, containing multiple characters. This is where the string variable type comes into play.
A string is the “real” text variable type. Unlike char, which represents a single character, a String can contain a word, a phrase, or even a complete paragraph.
In many programming languages, a string is simply a collection of chars. For example, in C.
However, to facilitate the handling and manipulation of text strings, programming languages generally provide more complex objects designed to work with text (which are also built around a collection of chars).
Example of text types
In languages descended from C, such as C++, C# or Java, both types exist, char and string. For example, this is how you would create a variable of each type in C#
char myCharacter = 'A';
string myString = "Hello, world!";
Note that in these languages, the value of a char is enclosed in ', while string values are enclosed in ".
This is identical to the case in C++, with the exception that string is defined in the std namespace.
char myCharacter = 'A';
std::string myString = "Hello, world!";
In JavaScript, only the string type exists, and there is no specific char type. Additionally, for value usage, we can use ', ", or ` interchangeably.
let myCharacter = 'A';
let myString = "Hello, world!";
Similarly, in Python, only the string type exists. To indicate values, we can use ' or " interchangeably.
myCharacter = 'A'
myString = "Hello, world!"
