Strings in Dart



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.


What is a String

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.


Creating Strings

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.''';


Example 1: Initializing Strings

  1. Create a string variable and initialize it with a value.
  2. Print the string variable using print.

Dart Program

void main() {
    String str = 'Hello, world!';
    print(str);
}

Output

Hello, world!


Example 2: Accessing Characters in a String

  1. Create a string variable and initialize it with a value.
  2. Access and print individual characters using array indexing.

Dart Program

void main() {
    String str = 'Hello';
    print(str[0]); // Accessing using array indexing
    print(str[1]);
}

Output

H
e


Example 3: Modifying Strings

  1. Create a string variable and initialize it with a value.
  2. Strings in Dart are immutable, so create a new string with the modified value.
  3. Print the modified string.

Dart Program

void main() {
    String str = 'Hello';
    str = 'J' + str.substring(1); // Modifying individual character
    str += ' World!'; // Appending new characters
    print(str);
}

Output

Jello World!


Example 4: String Concatenation

  1. Create two string variables and initialize them with values.
  2. Concatenate the strings using the + operator or string interpolation.
  3. Print the concatenated string.

Dart Program

void main() {
    String str1 = 'Hello';
    String str2 = ' World!';
    String str3 = str1 + str2; // Concatenating strings
    print(str3);
}

Output

Hello World!


Example 5: Finding Substrings

  1. Create a string variable and initialize it with a value.
  2. Use the indexOf method to find a substring.
  3. Print the position of the found substring.

Dart Program

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');
    }
}

Output

Found 'world' at position: 7


Example 6: String Length

  1. Create a string variable and initialize it with a value.
  2. Use the length property to get the length of the string.
  3. Print the length of the string.

Dart Program

void main() {
    String str = 'Hello, world!';
    print('Length of the string: ${str.length}'); // Getting string length
}

Output

Length of the string: 13