Strings and Text Manipulation
Explore Dart strings by mastering character sequences, escape characters, concatenation, and interpolation. Understand string length, indexing, and immutability while using built-in methods. This lesson helps you manipulate and format text efficiently in Dart applications.
In programming, we use the term String to describe any sequence of characters. We can think of a string as a necklace made of beads, where each bead represents a single character, such as a letter, number, punctuation mark, or even a space.
Technically, a Dart string is a sequence of UTF-16 code units. This encoding allows Dart to represent a vast range of characters from languages all over the world, as well as symbols and emojis.
At face value, string literals are raw text encapsulated in quotation marks. We use them to display messages, process user input, and manage any textual data in our apps.
Escaping characters
We can define a string using either single quotes (') or double quotes ("). However, we must be careful when our text actually contains a quotation mark, such as an apostrophe.
If we use single quotes to wrap a string that contains an apostrophe, the compiler will mistake the apostrophe for the end of the string. We can fix this by wrapping the text in double quotes, or we can use the escape character (\). The escape character tells the compiler to treat the next symbol as regular text.
We can see these different approaches in our main.dart file.
Line 2: We declare a variable named
basicand assign it a standard string literal using double quotes.Line 3: We use single quotes to define the string. We place a backslash
\right before the apostrophe in "It's" so the compiler does not end the string prematurely. ...