RosettaCodeData/Task/Binary-strings/D/binary-strings.d

46 lines
1.3 KiB
D
Raw Permalink Normal View History

2015-02-20 00:35:01 -05:00
void main() /*@safe*/ {
import std.array: empty, replace;
import std.string: representation, assumeUTF;
2013-04-10 16:57:12 -07:00
// String creation (destruction is usually handled by
2015-02-20 00:35:01 -05:00
// the garbage collector).
2013-04-10 16:57:12 -07:00
ubyte[] str1;
2015-02-20 00:35:01 -05:00
// String assignments.
str1 = "blah".dup.representation;
// Hex string, same as "\x00\xFB\xCD\x32\xFD\x0A"
// whitespace and newlines are ignored.
2013-04-10 16:57:12 -07:00
str1 = cast(ubyte[])x"00 FBCD 32FD 0A";
2015-02-20 00:35:01 -05:00
// String comparison.
2013-04-10 16:57:12 -07:00
ubyte[] str2;
2015-02-20 00:35:01 -05:00
if (str1 == str2) {} // Strings equal.
2013-04-10 16:57:12 -07:00
2015-02-20 00:35:01 -05:00
// String cloning and copying.
str2 = str1.dup; // Copy entire string or array.
2013-04-10 16:57:12 -07:00
// Check if a string is empty
2015-02-20 00:35:01 -05:00
if (str1.empty) {} // String empty.
if (str1.length) {} // String not empty.
if (!str1.length) {} // String empty.
2013-04-10 16:57:12 -07:00
2015-02-20 00:35:01 -05:00
// Append a ubyte to a string.
2013-04-10 16:57:12 -07:00
str1 ~= x"0A";
str1 ~= 'a';
2015-02-20 00:35:01 -05:00
// Extract a substring from a string.
str1 = "blork".dup.representation;
// This takes off the first and last bytes and
// assigns them to the new ubyte string.
// This is just a light slice, no string data copied.
ubyte[] substr = str1[1 .. $ - 1];
2013-04-10 16:57:12 -07:00
// Replace every occurrence of a ubyte (or a string)
2015-02-20 00:35:01 -05:00
// in a string with another string.
str1 = "blah".dup.representation;
replace(str1.assumeUTF, "la", "al");
2013-04-10 16:57:12 -07:00
2015-02-20 00:35:01 -05:00
// Join two strings.
2013-04-10 16:57:12 -07:00
ubyte[] str3 = str1 ~ str2;
}