In this tutorial, we will learn about strings in Dart. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.
A string in Dart is a sequence of characters. Strings in Dart are immutable, meaning their values cannot be changed once created. Strings are used for storing and handling text data.
Strings can be created in Dart using single or double quotes:
String str = 'Hello, world!';
String str2 = "Hello, world!";
Strings can also be created using triple quotes for multi-line strings:
String str3 = '''This is a
multi-line string.''';
print
.void main() {
String str = 'Hello, world!';
print(str);
}
Hello, world!
void main() {
String str = 'Hello';
print(str[0]); // Accessing using array indexing
print(str[1]);
}
H e
void main() {
String str = 'Hello';
str = 'J' + str.substring(1); // Modifying individual character
str += ' World!'; // Appending new characters
print(str);
}
Jello World!
+
operator or string interpolation.void main() {
String str1 = 'Hello';
String str2 = ' World!';
String str3 = str1 + str2; // Concatenating strings
print(str3);
}
Hello World!
indexOf
method to find a substring.void main() {
String str = 'Hello, world!';
int pos = str.indexOf('world'); // Finding substring
if (pos != -1) {
print('Found 'world' at position: $pos');
} else {
print('Substring not found');
}
}
Found 'world' at position: 7
length
property to get the length of the string.void main() {
String str = 'Hello, world!';
print('Length of the string: ${str.length}'); // Getting string length
}
Length of the string: 13