String Basics
Strings are one of the most fundamental data types in Dart, used to represent text. Think of strings as a sequence of characters - like words, sentences, or any text you might want to work with in your program.
What is a String?
A string in Dart is a sequence of UTF-16 code units. In simple terms, it's just text! Whether it's a single character, a word, a sentence, or even an entire paragraph - it's all considered a string.
Creating Strings
In Dart, you can create strings using either single quotes (') or double quotes ("). Both work exactly the same way:
String greeting = 'Hello, World!';
String message = "Welcome to Dart programming!";
String singleChar = 'A';
String emptyString = '';
Multi-line Strings
Sometimes you need to work with text that spans multiple lines. Dart provides triple quotes for this:
String multiLine = '''
This is a multi-line string.
It can span across multiple lines
without any special escape characters.
''';
String anotherMultiLine = """
You can also use triple double quotes
for multi-line strings.
Both work the same way!
""";
Raw Strings
Raw strings are useful when you want to include special characters without them being interpreted as escape sequences. Just prefix your string with r:
String rawString = r'This is a raw string with \n and \t';
String filePath = r'C:\Users\Documents\file.txt';
String Properties
Strings come with some handy built-in properties:
String text = 'Hello Dart';
print(text.length); // Output: 10
print(text.isEmpty); // Output: false
print(text.isNotEmpty); // Output: true
String empty = '';
print(empty.isEmpty); // Output: true
Accessing Characters
You can access individual characters in a string using square brackets with an index (starting from 0):
String word = 'Dart';
print(word[0]); // Output: D
print(word[1]); // Output: a
print(word[2]); // Output: r
print(word[3]); // Output: t
String Concatenation
You can combine strings using the + operator:
String firstName = 'John';
String lastName = 'Doe';
String fullName = firstName + ' ' + lastName;
print(fullName); // Output: John Doe
Escape Sequences
Sometimes you need to include special characters in your strings. Use escape sequences with a backslash (\):
| Escape Sequence | Description |
|---|---|
\n | New line |
\t | Tab |
\' | Single quote |
\" | Double quote |
\\ | Backslash |
String text = 'She said, "Hello!\nHow are you?"';
String path = 'C:\\Users\\Documents';
String quote = 'It\'s a beautiful day!';
String Comparison
You can compare strings using comparison operators:
String str1 = 'apple';
String str2 = 'banana';
String str3 = 'apple';
print(str1 == str3); // Output: true
print(str1 == str2); // Output: false
print(str1.compareTo(str2)); // Output: negative number (str1 < str2)
Strings are case-sensitive, so 'Hello' and 'hello' are considered different strings. Understanding these string basics will give you a solid foundation for working with text in your Dart programs!