Buscar..


Observaciones

  • Las cuerdas en D son inmutables; utilizar .dup hacer una mutable char matriz si desea editar en el lugar.

Invertir una cadena

string se define como alias string = immutable(char)[]; : así que necesitas usar dup para hacer una matriz de caracteres mutable, antes de que pueda revertirse:

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;

}

Prueba de una cadena vacía o nula

Cuerda vacía

La cadena vacía no es nula pero tiene longitud cero:

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

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

Cadena nula

string nullString = null;

una cadena nula es nula (De Lapalisse)

assert(nullString is null);

pero, a diferencia de C #, leer la longitud de una cadena nula no genera error:

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

Prueba de vacío o nulo


if (emptyOrNullString.length == 0) {
}

// or
if (emptyOrNullString.length) {
}

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

Prueba para nulo

if (nullString is null) {
}

Referencias

Convertir cadena a ubyte [] y viceversa

Cadena a ubyte[] inmutable 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

Cadena a 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[] a cadena

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

Referencias



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow