乐闻世界logo
搜索文章和话题

How to remove all whitespace of a string in Dart?

1个答案

1

There are several methods to remove all spaces from a string in Dart. I will introduce two common approaches and provide corresponding code examples.

Method 1: Using the replaceAll() Function

This is a straightforward approach. You can use the replaceAll() method of the String class. This method allows you to specify the substring to replace (here, a space) and the replacement substring (here, an empty string).

dart
String removeSpaces(String input) { return input.replaceAll(' ', ''); }

Example:

dart
void main() { String originalString = "Hello World! This is a test string."; String stringWithoutSpaces = removeSpaces(originalString); print(stringWithoutSpaces); // Output: HelloWorld!Thisisateststring. }

Method 2: Using Regular Expressions

If you want to remove all types of whitespace characters (including spaces, tabs, etc.), using a regular expression may be a more comprehensive solution. In Dart, you can use the replaceAll() method combined with a regular expression to achieve this.

dart
String removeWhitespace(String input) { return input.replaceAll(RegExp(r'\s+'), ''); }

Example:

dart
void main() { String originalString = "Hello World! This is a test string.\tNew line here."; String stringWithoutWhitespace = removeWhitespace(originalString); print(stringWithoutWhitespace); // Output: HelloWorld!Thisisateststring.Newlinehere. }

In this example, \s+ is a regular expression that matches one or more of any whitespace characters.

Both methods can effectively remove spaces or whitespace characters as needed. The choice depends on specific requirements: if you only need to remove spaces, the first method suffices; if you need to remove all types of whitespace characters, the second method is more appropriate.

2024年7月19日 13:18 回复

你的答案