D Language
Smyczki
Szukaj…
Uwagi
- Ciągi w D są niezmienne; użyj
.dup
aby utworzyć.dup
tablicęchar
jeśli chcesz edytować w miejscu.
Odwracanie ciągu
string
jest zdefiniowany jako alias string = immutable(char)[];
: więc musisz użyć dup
aby utworzyć zmienną tablicę char, zanim będzie można ją odwrócić:
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;
}
Sprawdź, czy łańcuch jest pusty lub pusty
Pusta struna
Pusty ciąg nie jest pusty, ale ma zerową długość:
string emptyString = "";
// an empty string is not null...
assert(emptyString !is null);
// ... but it has zero lenght
assert(emptyString.length == 0);
Ciąg zerowy
string nullString = null;
ciąg zerowy jest zerowy (De Lapalisse)
assert(nullString is null);
ale w przeciwieństwie do C #, odczytanie łańcucha zerowego nie generuje błędu:
assert(nullString.length == 0);
assert(nullString.empty);
Sprawdź, czy jest pusta lub pusta
if (emptyOrNullString.length == 0) {
}
// or
if (emptyOrNullString.length) {
}
// or
import std.array;
if (emptyOrNullString.empty) {
}
Test na zero
if (nullString is null) {
}
Bibliografia
Konwertuj ciąg znaków na ubyte [] i odwrotnie
Ciąg do niezmiennego 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
Ciąg do 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[]
na ciąg znaków
ubyte[] stream = [ 0x75, 0x6e, 0x6f, 0x67];
string us = cast(string)stream;
assert(us == "unog");
Bibliografia
Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow