How to strip whitespace of string in D language
Overview
In Dlang, the whitespace includes the following Unicode category:
- C0: tab, vertical tab, form feed, carriage return, and linefeed characters.
- Zs: Space separator
- Zl: Line separator
- Zp: Paragraph separator
- NEL(U+0085): NEXT LINE
We use the strip method present in the std.string module to remove the whitespace or specific characters from the start and end of the string.
Syntax
string strip(str, chars, leftChars, rightChars);
strip method syntax
Parameters:
This method takes four parameters.
str: String in which the characters are to be stripped.chars: String of characters to be stripped from the start and end of source string.leftChars: String of characters to be stripped from the start of the source string.rightChars: String of characters to be stripped at the end of the source string.
The last three arguments are optional, if that is skipped, by default, the whitespace at the start and end of the string is removed.
Return value
This method returns a string value. The returned string is created by stripping the given characters from the start and end of the source string.
Example
The code given below demonstrates how to remove whitespace from the string in Dlang.
import std.stdio;import std.string;void main(){string str = " this is a string ";writefln("The string before stripping: \"%s\"", str);str = strip(str);writefln("The string after stripping: \"%s\"", str);}
Explanation
- Lines 1 and 2: Import the
stdioandstringmodule. Thestdiomodule is used to print the value to output and the string module contains thestripmethod. - Line 5: Create a variable with the name
strand assign a string with whitespace at the start and end, as a value to the variable. - Line 7: Use the
stripmethod with thestras the argument. This method will remove all the whitespace at the start and end of the string.