Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

strip
dlang
whitespace
communitycreator

How to strip whitespace of string in D language

Programming Bytes

Overview

In Dlang, the whitespace includes the following Unicode category:

  1. C0: tab, vertical tab, form feed, carriage return, and linefeed characters.
  2. Zs: Space separator
  3. Zl: Line separator
  4. Zp: Paragraph separator
  5. 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.

  1. str: String in which the characters are to be stripped.
  2. chars: String of characters to be stripped from the start and end of source string.
  3. leftChars: String of characters to be stripped from the start of the source string.
  4. 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);
}
Using the strip method to remove the whitespace of the string

Explanation

  • Lines 1 and 2: Import the stdio and string module. The stdio module is used to print the value to output and the string module contains the strip method.
  • Line 5: Create a variable with the name str and assign a string with whitespace at the start and end, as a value to the variable.
  • Line 7: Use the strip method with the str as the argument. This method will remove all the whitespace at the start and end of the string.

RELATED TAGS

strip
dlang
whitespace
communitycreator
RELATED COURSES

View all Courses

Keep Exploring