Recherche…


Remarques

  • Les chaînes en D sont immuables; utiliser .dup pour faire un mutable char tableau si vous souhaitez modifier en place.

Inverser une chaîne

string est définie comme alias string = immutable(char)[]; : il faut donc utiliser dup pour créer un tableau de caractères mutable avant de pouvoir l'inverser:

import std.stdio;
import std.string;

int main() {

    string x = "Hello world!";
    char[] x_rev = x.dup.reverse;
    
    writeln(x_rev); // !dlrow olleH
    
    return 0;

}

Test d'une chaîne vide ou nulle

Chaîne vide

La chaîne vide n'est pas nulle mais a une longueur nulle:

string emptyString = "";
// an empty string is not null...
assert(emptyString !is null);

// ... but it has zero lenght
assert(emptyString.length == 0);

Chaîne nulle

string nullString = null;

une chaîne vide est null (De Lapalisse)

assert(nullString is null);

mais, contrairement à C #, lire la longueur d'une chaîne vide ne génère pas d'erreur:

assert(nullString.length == 0);
assert(nullString.empty);

Test pour vide ou null


if (emptyOrNullString.length == 0) {
}

// or
if (emptyOrNullString.length) {
}

// or
import std.array;
if (emptyOrNullString.empty) {
}

Test pour null

if (nullString is null) {
}

Les références

Convertir une chaîne en octets [] et vice versa

Chaîne à ubyte[] immuable ubyte[]

string s = "unogatto";
immutable(ubyte[]) ustr = cast(immutable(ubyte)[])s;

assert(typeof(ustr).stringof == "immutable(ubyte[])");
assert(ustr.length == 8);
assert(ustr[0] == 0x75); //u
assert(ustr[1] == 0x6e); //n
assert(ustr[2] == 0x6f); //o
assert(ustr[3] == 0x67); //g
assert(ustr[7] == 0x6f); //o

Chaîne de ubyte[]

string s = "unogatto";
ubyte[] mustr = cast(ubyte[])s;

assert(typeof(mustr).stringof == "ubyte[]");

assert(mustr.length == 8);
assert(mustr[0] == 0x75);
assert(mustr[1] == 0x6e);
assert(mustr[2] == 0x6f);
assert(mustr[3] == 0x67);
assert(mustr[7] == 0x6f);

ubyte[] pour enchaîner

ubyte[] stream = [ 0x75, 0x6e, 0x6f, 0x67];
string us  = cast(string)stream;
assert(us == "unog");

Les références



Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow