String manipulation is a fundamental aspect of programming. In Dart, strings are used to represent sequences of characters and can be manipulated in various ways. This document covers basic string operations, string immutability, concatenation, comparison, case manipulation, and advanced string operations.
Basic String Operations
Creating Strings
- Literal Strings: You can create strings using single or double quotes.
Syntax:
String singleQuoteString = 'Hello, World!'; String doubleQuoteString = "Hello, World!";
- String Interpolation: This allows you to embed expressions within strings using the
$
symbol.Syntax:
String name = 'Alice'; String greeting = 'Hello, $name!'; String mathExpression = 'The sum of 1 and 2 is ${1 + 2}.';
- Multi-line Strings: You can create multi-line strings using triple quotes.
Syntax:
String multiLineString = '''This is a string that spans multiple lines.''';
Accessing Characters
- Using Indexing: You can access individual characters using their index, starting from 0.
Syntax:
String str = 'Dart'; String firstCharacter = str[0]; // 'D'
- Using the
codeUnits
Property: This provides a list of the UTF-16 code units of the string.Syntax:
List<int> codeUnits = str.codeUnits; // [68, 97, 114, 116]
String Length
- Using the
length
Property: You can obtain the number of characters in a string.Syntax:
int length = str.length; // 4
String Immutability and Concatenation
Immutability
Strings in Dart are immutable, meaning they cannot be modified in place. Instead, any operations that appear to modify a string will create a new string.
- Creating New Strings: When you concatenate or manipulate strings, new strings are produced.
Example:
String original = 'Hello'; String modified = original + ' World!'; // Creates a new string
Concatenation
- Using the
+
Operator: You can concatenate strings using the+
operator.Syntax:
String combined = 'Hello' + ' ' + 'World!'; // 'Hello World!'
- Using the
join()
Method on a List of Strings: This method concatenates a list of strings with a specified separator.Syntax:
List<String> words = ['Hello', 'World']; String joined = words.join(' '); // 'Hello World'
- Using String Interpolation: You can also concatenate strings using interpolation.
Syntax:
String name = 'Alice'; String greeting = 'Hello, $name!'; // 'Hello, Alice!'
String Comparison and Case Manipulation
Comparison
- Using the
==
Operator: This checks for equality between two strings.Syntax:
bool isEqual = 'Hello' == 'Hello'; // true
- Using the
compareTo()
Method: This provides lexicographic ordering.Syntax:
int comparison = 'apple'.compareTo('banana'); // negative value
- Using Regular Expressions: You can use regex for pattern matching.
Syntax:
RegExp regExp = RegExp(r'^[A-Z]'); bool matches = regExp.hasMatch('Hello'); // true
Case Manipulation
- Converting to Uppercase/Lowercase: Use
toUpperCase()
andtoLowerCase()
.Syntax:
String upper = 'hello'.toUpperCase(); // 'HELLO' String lower = 'WORLD'.toLowerCase(); // 'world'
- Checking Case: You can check for substring presence in a case-insensitive manner using
contains()
.Syntax:
dart
Copy
bool containsHello = 'Hello World'.toLowerCase().contains('hello'); // true
Advanced String Operations
Substring Extraction
- Using the
substring()
Method: This allows you to extract a portion of a string.Syntax:
String str = 'Dart Programming'; String subStr = str.substring(0, 4); // 'Dart'
String Formatting
- Using the
format()
Method: Dart does not have a built-in format method like some other languages, but you can use string interpolation.Syntax:
String formatted = 'The price is \$${price}'; // Uses interpolation
Regular Expressions
- Creating and Using Regular Expressions: Use the
RegExp
class for pattern matching and replacement.Syntax:
RegExp regExp = RegExp(r'\d+'); // Matches one or more digits String input = 'There are 2 apples'; Iterable<Match> matches = regExp.allMatches(input); // Finds all matches
String Splitting and Joining
- Using the
split()
Method: This creates a list of substrings based on a delimiter.Syntax:
String str = 'apple,banana,cherry'; List<String> fruits = str.split(','); // ['apple', 'banana', 'cherry']
- Using the
join()
Method: You can concatenate a list of strings with a separator.Syntax:
List<String> fruits = ['apple', 'banana', 'cherry']; String joinedFruits = fruits.join(', '); // 'apple, banana, cherry'
Example Program
Here’s a complete example that demonstrates various string manipulation techniques:
void main() {
// Creating strings String name = 'Alice';
String greeting = 'Hello, $name!'; // String interpolation String multiLine = '''This is
a multi-line string.''';
print(greeting);
print(multiLine);
// Accessing characters print('First character: ${name[0]}'); // 'A' print('Code units: ${name.codeUnits}'); // [65, 108, 105, 99, 101]
// String length print('Length of name: ${name.length}'); // 5
// String concatenation String fullGreeting = greeting + ' Welcome!';
print(fullGreeting); // 'Hello, Alice! Welcome!'
List<String> words = ['Dart', 'is', 'fun'];
print(words.join(' ')); // 'Dart is fun'
// String comparison print('Comparison: ${'apple'.compareTo('banana')}'); // negative value
// Case manipulation print('Uppercase: ${name.toUpperCase()}'); // 'ALICE' print('Contains "alice": ${name.toLowerCase().contains('alice')}'); // true
// Substring extraction String substring = name.substring(1, 3); // 'li' print('Substring: $substring');
// Regular expressions RegExp regExp = RegExp(r'A\w+');
String text = 'Apples are A1 and A2';
print('Matches: ${regExp.allMatches(text)}');
// String splitting and joining String csv = 'apple,banana,cherry';
List<String> fruits = csv.split(',');
print('Fruits: $fruits'); // ['apple', 'banana', 'cherry'] print('Joined Fruits: ${fruits.join(', ')}'); // 'apple, banana, cherry' }
Conclusion
String manipulation is a vital skill in Dart programming. Understanding how to create, access, modify, and compare strings can enhance your ability to work with text data effectively. By practicing the examples provided, you can become proficient in string manipulation techniques, which are essential for various applications in Dart.
PLAY QUIZ