How to Perform String Manipulation In Dart?

9 minutes read

String manipulation in Dart involves various operations to manipulate the contents of a string. Here are some common techniques:

  1. Concatenation: You can concatenate multiple strings using the '+' operator. For example:
1
2
3
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2; // "Hello World"


  1. Length: To get the length of a string, you can use the length property. For example:
1
2
String str = "Hello";
int stringLength = str.length; // 5


  1. Substring: You can extract a substring from a string using the substring() method. The method takes the start and end indices and returns the desired substring. For example:
1
2
String str = "Hello World";
String subStr = str.substring(6, 11); // "World"


  1. Case conversion: Dart provides methods to convert a string to uppercase or lowercase using toUpperCase() and toLowerCase() methods, respectively. For example:
1
2
3
String str = "Hello World";
String upperCaseStr = str.toUpperCase(); // "HELLO WORLD"
String lowerCaseStr = str.toLowerCase(); // "hello world"


  1. Splitting: You can split a string into multiple substrings using a delimiter with the split() method. For example:
1
2
String str = "Hello,World,Dart";
List<String> splitStr = str.split(","); // ["Hello", "World", "Dart"]


  1. Parsing: Dart provides methods to parse strings into other data types like integers and doubles. For example:
1
2
3
4
5
String str = "10";
int intValue = int.parse(str); // 10

String doubleStr = "3.14";
double doubleValue = double.parse(doubleStr); // 3.14


  1. Replacing: Dart provides the replace() method to replace occurrences of a substring within a string. For example:
1
2
String str = "Hello World";
String replacedStr = str.replaceFirst("World", "Dart"); // "Hello Dart"


These are just a few examples of string manipulation techniques in Dart. By combining these methods creatively, you can perform a wide range of manipulations on strings according to your requirements.

Best Dart Books to Read in 2024

1
Flutter and Dart Cookbook: Developing Full-Stack Applications for the Cloud

Rating is 5 out of 5

Flutter and Dart Cookbook: Developing Full-Stack Applications for the Cloud

2
Flutter Cookbook: Over 100 proven techniques and solutions for app development with Flutter 2.2 and Dart

Rating is 4.9 out of 5

Flutter Cookbook: Over 100 proven techniques and solutions for app development with Flutter 2.2 and Dart

3
Quick Start Guide to Dart Programming: Create High-Performance Applications for the Web and Mobile

Rating is 4.8 out of 5

Quick Start Guide to Dart Programming: Create High-Performance Applications for the Web and Mobile

4
Dart: Up and Running: A New, Tool-Friendly Language for Structured Web Apps

Rating is 4.7 out of 5

Dart: Up and Running: A New, Tool-Friendly Language for Structured Web Apps

5
The Dart Programming Language

Rating is 4.6 out of 5

The Dart Programming Language

6
Mastering Dart: A Comprehensive Guide to Learn Dart Programming

Rating is 4.5 out of 5

Mastering Dart: A Comprehensive Guide to Learn Dart Programming

7
Flutter Cookbook: 100+ step-by-step recipes for building cross-platform, professional-grade apps with Flutter 3.10.x and Dart 3.x, 2nd Edition

Rating is 4.4 out of 5

Flutter Cookbook: 100+ step-by-step recipes for building cross-platform, professional-grade apps with Flutter 3.10.x and Dart 3.x, 2nd Edition

8
Flutter for Beginners: An introductory guide to building cross-platform mobile applications with Flutter 2.5 and Dart, 2nd Edition

Rating is 4.3 out of 5

Flutter for Beginners: An introductory guide to building cross-platform mobile applications with Flutter 2.5 and Dart, 2nd Edition


How to remove whitespace from a string in Dart?

To remove whitespace from a string in Dart, you can use the replaceAll() method with a regular expression pattern that matches whitespace characters. Here's an example:

1
2
3
4
5
void main() {
  String str = '   hello     world   ';
  String trimmedStr = str.replaceAll(RegExp(r'\s+'), '');
  print(trimmedStr); // Output: helloworld
}


In the above example, the replaceAll() method is used with a regular expression pattern RegExp(r'\s+'). The \s matches any whitespace character, and the + specifies that one or more occurrences of whitespace should be replaced. The replacement string is specified as an empty string '' to remove the whitespace characters.


Note that if you want to remove only leading and trailing whitespace, you can use the trim() method instead:

1
2
3
4
5
void main() {
  String str = '   hello     world   ';
  String trimmedStr = str.trim();
  print(trimmedStr); // Output: hello     world
}


In this case, the trim() method removes leading and trailing whitespaces from the string, but preserves any whitespace characters within the string.


How to replace a substring within a string in Dart?

In Dart, you can use the replaceFirst method of the String class to replace a substring within a string. Here's an example:

1
2
3
4
5
6
7
8
9
void main() {
  String originalString = 'Hello, World!';
  String substringToReplace = 'World';
  String replacementSubstring = 'Everyone';

  String newString = originalString.replaceFirst(substringToReplace, replacementSubstring);

  print(newString); // Output: Hello, Everyone!
}


In this example, we first define the original string 'Hello, World!'. Then, we specify the substring 'World' that we want to replace and the replacement substring 'Everyone'. We use the replaceFirst method to replace the first occurrence of the substring in the original string, resulting in the new string 'Hello, Everyone!'. Finally, we print the new string using print(newString).


How to format a DateTime object as a string in Dart?

To format a DateTime object as a string in Dart, you can use the intl package which provides the DateFormat class. Here's an example of how to format a DateTime object:

  1. Import the intl package:
1
import 'package:intl/intl.dart';


  1. Create a DateFormat object with the desired format:
1
var formatter = DateFormat('yyyy-MM-dd HH:mm:ss');


  1. Format the DateTime object using the format method:
1
2
var now = DateTime.now();
var formattedDate = formatter.format(now);


In this example, the format 'yyyy-MM-dd HH:mm:ss' represents the year, month, day, hour, minute, and second of the DateTime object. You can customize the format pattern according to your needs.


The formattedDate variable will contain the formatted DateTime as a string.


How to format a number as a currency string in Dart?

To format a number as a currency string in Dart, you can use the NumberFormat class from the intl package. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import 'package:intl/intl.dart';

void main() {
  double number = 1234.56;
  
  // create a NumberFormat instance for currency formatting
  final currencyFormat = NumberFormat.currency(locale: 'en_US', symbol: '\$');

  // format the number as a currency string
  String result = currencyFormat.format(number);
  
  print(result); // $1,234.56
}


In this example, we create a NumberFormat instance called currencyFormat and set the locale parameter to 'en_US' for US English formatting. The symbol parameter is set to '$' to represent the currency symbol.


Then, we use the format method of the currencyFormat instance to format the number as a currency string. The resulting string is stored in the result variable.


Finally, we print the result, which would display '$1,234.56'.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

To send emails via Gmail from Dart, you can use the mailer package. Here are the steps to achieve this:Set up your Dart project by creating a new Dart file and importing the necessary packages. import &#39;package:mailer/mailer.dart&#39;; import &#39;package:m...
Dart DevTools is a powerful tool for debugging Dart applications. It provides a comprehensive set of features to help you understand and analyze the behavior of your code during runtime. Here&#39;s an overview of how to use Dart DevTools for debugging:Installa...
Unit testing is an essential part of the software development process as it helps ensure the correctness of individual units or components in an application. In Dart, unit testing can be performed using the built-in testing framework called test.To perform uni...