Dart provides several built-in string functions that you can use to manipulate and work with strings. Here are some commonly used string functions in Dart:
1. length : The `
length
` property returns the number of characters in a string.
String str = 'Hello, Dart!';
print(str.length); // Output: 13​
2. toUpperCase() / toLowerCase() : These methods return a new string with all characters converted to uppercase or lowercase, respectively.
String str = 'Hello, Dart!';
print(str.toUpperCase()); // Output: HELLO, DART!
print(str.toLowerCase()); // Output: hello, dart!​
3. trim() : The `
trim()
` method removes leading and trailing whitespace characters from a string.
String str = ' Hello, Dart! ';
print(str.trim()); // Output: Hello, Dart!​
4. split() : The `
split()
` method splits a string into a list of substrings based on a specified delimiter.
String str = 'apple,banana,orange';
List fruits = str.split(',');
print(fruits); // Output: [apple, banana, orange]​
5. substring() : The `
substring()
` method returns a new string that is a substring of the original string, starting at a specified index and optionally ending at another index.
String str = 'Hello, Dart!';
print(str.substring(7)); // Output: Dart!
print(str.substring(0, 5)); // Output: Hello​
6. indexOf() / lastIndexOf() : These methods return the index of the first/last occurrence of a specified substring within a string. If the substring is not found, they return -1.
String str = 'Hello, Dart!';
print(str.indexOf('Dart')); // Output: 7
print(str.lastIndexOf('l')); // Output: 10​
7. startsWith() / endsWith() : These methods check if a string starts or ends with a specified substring, returning a boolean result.
String str = 'Hello, Dart!';
print(str.startsWith('Hello')); // Output: true
print(str.endsWith('!')); // Output: true​
8. contains() : The `
contains()
` method checks if a string contains a specified substring, returning a boolean result.
String str = 'Hello, Dart!';
print(str.contains('Dart')); // Output: true
print(str.contains('Python')); // Output: false​
9. replace() : The `
replace()
` method replaces all occurrences of a specified substring with another substring.
String str = 'Hello, Dart!';
String newStr = str.replaceFirst('Dart', 'World');
print(newStr); // Output: Hello, World!​