String Functions in D Programming Language

The standard library’s std.string module provides many useful string-related functions. Here are some examples to give you a sense of the module.

import std.stdio;
import std.string;
import std.array;

void main()
{
    // We alias writeln to a shorter name as we'll use it a lot below.
    alias p = writeln;

    // Here's a sample of the functions available in std.string and std.array.
    // Since these are functions from the modules, not methods on the string
    // object itself, we need to pass the string in question as the first
    // argument to the function. You can find more functions in the
    // std.string and std.array module docs.

    p("Contains:  ", "test".canFind("es"));
    p("Count:     ", "test".count("t"));
    p("HasPrefix: ", "test".startsWith("te"));
    p("HasSuffix: ", "test".endsWith("st"));
    p("Index:     ", "test".indexOf("e"));
    p("Join:      ", ["a", "b"].join("-"));
    p("Repeat:    ", "a".repeat(5));
    p("Replace:   ", "foo".replace("o", "0"));
    p("Replace:   ", "foo".replaceFirst("o", "0"));
    p("Split:     ", "a-b-c-d-e".split("-"));
    p("ToLower:   ", "TEST".toLower());
    p("ToUpper:   ", "test".toUpper());
}

When you run this program, you’ll get:

$ rdmd string_functions.d
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      ["a", "b", "c", "d", "e"]
ToLower:    test
ToUpper:    TEST

In this D version, we’ve used equivalent functions from the std.string and std.array modules. Some differences to note:

  1. D uses canFind instead of Contains.
  2. startsWith and endsWith are used instead of HasPrefix and HasSuffix.
  3. indexOf is used instead of Index.
  4. replace replaces all occurrences by default, while replaceFirst replaces only the first occurrence.
  5. The Split function returns an array of strings in D, which is why it’s displayed differently in the output.

These functions provide similar functionality to their counterparts, allowing you to manipulate strings effectively in D.