Post

String Manipulation and Collections

Essential for processing and formatting text data in programming,

String Manipulation and Collections

Importance

String manipulation is essential for processing and formatting text data in programming, such as generating messages, formatting user input, or performing text-based calculations.

Common Operations

  • Concatenation: Concatenation combines two or more strings into one. Dart uses the + operator for this.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
      void main() {
    String firstName = 'John';
    String lastName = 'Doe';
    
    // Concatenate two strings
    String fullName = firstName + ' ' + lastName;
    
    print('Full Name: $fullName'); // Output: Full Name: John Doe
      }
    
  • Interpolation String interpolation allows embedding variables directly within a string. Dart uses $ for simple variables and ${} for expressions.
1
2
3
4
5
6
7
8
9
10
11
12
13
  void main() {
  String name = 'Alice';
  int age = 30;

  // String interpolation with a variable
  String greeting = 'Hello, $name!';

  // String interpolation with an expression
  String message = 'In 5 years, you will be ${age + 5} years old.';

  print(greeting); // Output: Hello, Alice!
  print(message);  // Output: In 5 years, you will be 35 years old.
  }
  • Substring: The substring() method extracts a portion of a string by specifying start and end indices.
1
2
3
4
5
6
7
8
  void main() {
    String text = 'Hello, Dart programming!';

    // Extract a substring from index 7 to 11
    String subText = text.substring(7, 11);

    print('Substring: $subText'); // Output: Substring: Dart
  }
This post is licensed under CC BY 4.0 by the author.