Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

std.string

String handling functions.
CategoryFunctions
Searchingcolumn indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither 
ComparisonisNumeric 
Mutationcapitalize 
Pruning and Fillingcenter chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap 
Substitutionabbrev soundex soundexer succ tr translate 
MiscellaneousassumeUTF fromStringz lineSplitter representation splitLines toStringz 
Objects of typesstring,wstring, anddstring are value typesand cannot be mutated element-by-element. For using mutation during buildingstrings, usechar[],wchar[], ordchar[]. Thexxxstringtypes are preferable because they don't exhibit undesired aliasing, thusmaking code more robust.
The following functions are publicly imported:
ModuleFunctions
    Publicly imported functions
std.algorithmcmpcountendsWithstartsWith
std.arrayjoinreplacereplaceInPlacesplitempty
std.formatformatsformat
std.uniicmptoLowertoLowerInPlacetoUppertoUpperInPlace
There is a rich set of functions for string handling defined in other modules.Functions related to Unicode and ASCII are found instd.uniandstd.ascii, respectively. Other functions that have awider generality than just strings can be found instd.algorithmandstd.range.
See Also:
License:
Boost License 1.0.
Authors:
Walter Bright,Andrei Alexandrescu,Jonathan M Davis, and David L. 'SpottedTiger' Davis

Sourcestd/string.d

classStringException:object.Exception;
Exception thrown on errors in std.string functions.
Examples:
import std.exception : assertThrown;auto bad ="      a\n\tb\n   c";assertThrown!StringException(bad.outdent);
pure nothrow @nogc @system inout(Char)[]fromStringz(Char)(return scope inout(Char)*cString)
if (isSomeChar!Char);

pure nothrow @nogc @safe inout(Char)[]fromStringz(Char)(return scope inout(Char)[]cString)
if (isSomeChar!Char);
Parameters:
inout(Char)*cStringA null-terminated c-style string.
Returns:
A D-style array ofchar,wchar ordchar referencing the same string. The returned array will retain the same type qualifiers as the input.
Important Note: The returned array is a slice of the original buffer. The original data is not changed and not copied.
Examples:
writeln(fromStringz("foo\0"c.ptr));// "foo"cwriteln(fromStringz("foo\0"w.ptr));// "foo"wwriteln(fromStringz("foo\0"d.ptr));// "foo"dwriteln(fromStringz("福\0"c.ptr));// "福"cwriteln(fromStringz("福\0"w.ptr));// "福"wwriteln(fromStringz("福\0"d.ptr));// "福"d
Examples:
struct C{char[32] name;}writeln(C("foo\0"c).name.fromStringz());// "foo"cstruct W{wchar[32] name;}writeln(W("foo\0"w).name.fromStringz());// "foo"wstruct D{dchar[32] name;}writeln(D("foo\0"d).name.fromStringz());// "foo"d
pure nothrow @trusted immutable(char)*toStringz(scope const(char)[]s);
Parameters:
const(char)[]sA D-style string.
Returns:
A C-style null-terminated string equivalent tos.s must not contain embedded'\0''s as any C function will treat the first'\0' that it sees as the end of the string. Ifs.empty istrue, then a string containing only'\0' is returned.
Important Note: When passing achar* to a C function, and the C function keeps it around for any reason, make sure that you keep a reference to it in your D code. Otherwise, it may become invalid during a garbage collection cycle and cause a nasty bug when the C code tries to use it.
Examples:
import core.stdc.string : strlen;import std.conv : to;auto p =toStringz("foo");writeln(strlen(p));// 3const(char)[] foo ="abbzxyzzy";p =toStringz(foo[3 .. 5]);writeln(strlen(p));// 2string test ="";p =toStringz(test);writeln(*p);// 0test ="\0";p =toStringz(test);writeln(*p);// 0test ="foo\0";p =toStringz(test);assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);const string test2 ="";p =toStringz(test2);writeln(*p);// 0assert(toStringz([])istoStringz(""));
aliasCaseSensitive = std.typecons.Flag!"caseSensitive".Flag;
Flag indicating whether a search is case-sensitive.
ptrdiff_tindexOf(Range)(Ranges, dcharc, CaseSensitivecs = Yes.caseSensitive)
if (isInputRange!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range);

ptrdiff_tindexOf(C)(scope const(C)[]s, dcharc, CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!C);

ptrdiff_tindexOf(Range)(Ranges, dcharc, size_tstartIdx, CaseSensitivecs = Yes.caseSensitive)
if (isInputRange!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range);

ptrdiff_tindexOf(C)(scope const(C)[]s, dcharc, size_tstartIdx, CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!C);
Searches for a character in a string or range.
Parameters:
Rangesstring or InputRange of characters to search forc in
dcharccharacter to search for ins
size_tstartIdxindex to a well-formed code point ins to start searching from; defaults to 0
CaseSensitivecsspecifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive).
Returns:
Ifc is found ins, then the index of its first occurrence is returned. Ifc is not found orstartIdx is greater than or equal tos.length, then -1 is returned. If the parameters are not valid UTF, the result will still be either -1 or in the range [startIdx ..s.length], but will not be reliable otherwise.
Throws:
If the sequence starting atstartIdx does not represent a well-formed code point, then astd.utf.UTFException may be thrown.
See Also:
Examples:
import std.typecons : No;strings ="Hello World";writeln(indexOf(s, 'W'));// 6writeln(indexOf(s, 'Z'));// -1writeln(indexOf(s, 'w', No.caseSensitive));// 6
Examples:
import std.typecons : No;strings ="Hello World";writeln(indexOf(s, 'W', 4));// 6writeln(indexOf(s, 'Z', 100));// -1writeln(indexOf(s, 'w', 3, No.caseSensitive));// 6
ptrdiff_tindexOf(Range, Char)(Ranges, const(Char)[]sub)
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && isSomeChar!Char);

ptrdiff_tindexOf(Range, Char)(Ranges, const(Char)[]sub, in CaseSensitivecs)
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && isSomeChar!Char);

@safe ptrdiff_tindexOf(Char1, Char2)(const(Char1)[]s, const(Char2)[]sub, in size_tstartIdx)
if (isSomeChar!Char1 && isSomeChar!Char2);

@safe ptrdiff_tindexOf(Char1, Char2)(const(Char1)[]s, const(Char2)[]sub, in size_tstartIdx, in CaseSensitivecs)
if (isSomeChar!Char1 && isSomeChar!Char2);
Searches for a substring in a string or range.
Parameters:
Rangesstring or ForwardRange of characters to search forsub in
const(Char)[]subsubstring to search for ins
size_tstartIdxindex to a well-formed code point ins to start searching from; defaults to 0
CaseSensitivecsspecifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive)
Returns:
The index of the first occurrence ofsub ins. Ifsub is not found orstartIdx is greater than or equal tos.length, then -1 is returned. If the arguments are not valid UTF, the result will still be either -1 or in the range [startIdx ..s.length], but will not be reliable otherwise.
Throws:
If the sequence starting atstartIdx does not represent a well-formed code point, then astd.utf.UTFException may be thrown.
Bugs:
Does not work with case-insensitive strings where the mapping ofstd.uni.toLower andstd.uni.toUpper is not 1:1.
Examples:
import std.typecons : No;strings ="Hello World";writeln(indexOf(s,"Wo", 4));// 6writeln(indexOf(s,"Zo", 100));// -1writeln(indexOf(s,"wo", 3, No.caseSensitive));// 6
Examples:
import std.typecons : No;strings ="Hello World";writeln(indexOf(s,"Wo"));// 6writeln(indexOf(s,"Zo"));// -1writeln(indexOf(s,"wO", No.caseSensitive));// 6
pure @safe ptrdiff_tlastIndexOf(Char)(const(Char)[]s, in dcharc, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char);

pure @safe ptrdiff_tlastIndexOf(Char)(const(Char)[]s, in dcharc, in size_tstartIdx, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char);
Searches for the last occurrence of a character in a string.
Parameters:
const(Char)[]sstring to search forc in
dcharccharacter to search for ins
size_tstartIdxindex of a well-formed code point ins to start searching from; defaults to 0
CaseSensitivecsspecifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive)
Returns:
Ifc is found ins, then the index of its last occurrence is returned. Ifc is not found orstartIdx is greater than or equal tos.length, then -1 is returned. If the parameters are not valid UTF, the result will still be either -1 or in the range [startIdx ..s.length], but will not be reliable otherwise.
Throws:
If the sequence ending atstartIdx does not represent a well-formed code point, then astd.utf.UTFException may be thrown.
Examples:
import std.typecons : No;strings ="Hello World";writeln(lastIndexOf(s, 'l'));// 9writeln(lastIndexOf(s, 'Z'));// -1writeln(lastIndexOf(s, 'L', No.caseSensitive));// 9
Examples:
import std.typecons : No;strings ="Hello World";writeln(lastIndexOf(s, 'l', 4));// 3writeln(lastIndexOf(s, 'Z', 1337));// -1writeln(lastIndexOf(s, 'L', 7, No.caseSensitive));// 3
pure @safe ptrdiff_tlastIndexOf(Char1, Char2)(const(Char1)[]s, const(Char2)[]sub, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char1 && isSomeChar!Char2);

pure @safe ptrdiff_tlastIndexOf(Char1, Char2)(const(Char1)[]s, const(Char2)[]sub, in size_tstartIdx, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char1 && isSomeChar!Char2);
Searches for the last occurrence of a substring in a string.
Parameters:
const(Char1)[]sstring to search forsub in
const(Char2)[]subsubstring to search for ins
size_tstartIdxindex to a well-formed code point ins to start searching from; defaults to 0
CaseSensitivecsspecifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive)
Returns:
The index of the last occurrence ofsub ins. Ifsub is not found orstartIdx is greater than or equal tos.length, then -1 is returned. If the parameters are not valid UTF, the result will still be either -1 or in the range [startIdx ..s.length], but will not be reliable otherwise.
Throws:
If the sequence starting atstartIdx does not represent a well-formed code point, then astd.utf.UTFException may be thrown.
Bugs:
Does not work with case-insensitive strings where the mapping ofstd.uni.toLower andstd.uni.toUpper is not 1:1.
Examples:
import std.typecons : No;strings ="Hello World";writeln(lastIndexOf(s,"ll"));// 2writeln(lastIndexOf(s,"Zo"));// -1writeln(lastIndexOf(s,"lL", No.caseSensitive));// 2
Examples:
import std.typecons : No;strings ="Hello World";writeln(lastIndexOf(s,"ll", 4));// 2writeln(lastIndexOf(s,"Zo", 128));// -1writeln(lastIndexOf(s,"lL", 3, No.caseSensitive));// -1
pure @safe ptrdiff_tindexOfAny(Char, Char2)(const(Char)[]haystack, const(Char2)[]needles, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char && isSomeChar!Char2);

pure @safe ptrdiff_tindexOfAny(Char, Char2)(const(Char)[]haystack, const(Char2)[]needles, in size_tstartIdx, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char && isSomeChar!Char2);
Searches the stringhaystack for one of the characters inneedles starting at indexstartIdx. IfstartIdx is not given, it defaults to 0.
Parameters:
const(Char)[]haystackstring to search for needles in
const(Char2)[]needlescharacters to search for inhaystack
size_tstartIdxindex of a well-formed code point inhaystack to start searching from; defaults to 0
CaseSensitivecsspecifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive)
Returns:
The index of the first occurrence of any of the elements ofneedles inhaystack. If no element ofneedles is found orstartIdx is greater than or equal tohaystack.length, then -1 is returned. If the parameters are not valid UTF, the result will still be either -1 or in the range [startIdx ..haystack.length], but will not be reliable otherwise.
Throws:
If the sequence starting atstartIdx does not represent a well-formed code point, then astd.utf.UTFException may be thrown.
Examples:
import std.conv : to;ptrdiff_t i ="helloWorld".indexOfAny("Wr");writeln(i);// 5i ="öällo world".indexOfAny("lo ");writeln(i);// 4
Examples:
import std.conv : to;ptrdiff_t i ="helloWorld".indexOfAny("Wr", 4);writeln(i);// 5i ="Foo öällo world".indexOfAny("lh", 3);writeln(i);// 8
pure @safe ptrdiff_tlastIndexOfAny(Char, Char2)(const(Char)[]haystack, const(Char2)[]needles, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char && isSomeChar!Char2);

pure @safe ptrdiff_tlastIndexOfAny(Char, Char2)(const(Char)[]haystack, const(Char2)[]needles, in size_tstopIdx, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char && isSomeChar!Char2);
Searcheshaystack for the last occurrence of any of the characters inneedles.
Parameters:
const(Char)[]haystackstring to search needles in
const(Char2)[]needlescharacters to search for inhaystack
size_tstopIdxindex inhaystack to stop searching at (exclusive); defaults tohaystack.length
CaseSensitivecsspecifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive)
Returns:
The index of the last occurrence of any of the characters ofneedles inhaystack. If no character ofneedles is found orstopIdx is 0, then -1 is returned. If the parameters are not valid UTF, the result will still be in the range [-1 ..stopIdx], but will not be reliable otherwise.
Examples:
ptrdiff_t i ="helloWorld".lastIndexOfAny("Wlo");writeln(i);// 8i ="Foo öäöllo world".lastIndexOfAny("öF");writeln(i);// 8
Examples:
import std.conv : to;ptrdiff_t i ="helloWorld".lastIndexOfAny("Wlo", 4);writeln(i);// 3i ="Foo öäöllo world".lastIndexOfAny("öF", 3);writeln(i);// 0
pure @safe ptrdiff_tindexOfNeither(Char, Char2)(const(Char)[]haystack, const(Char2)[]needles, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char && isSomeChar!Char2);

pure @safe ptrdiff_tindexOfNeither(Char, Char2)(const(Char)[]haystack, const(Char2)[]needles, in size_tstartIdx, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char && isSomeChar!Char2);
Searcheshaystack for a character not inneedles.
Parameters:
const(Char)[]haystackstring to search for needles in
const(Char2)[]needlescharacters to search for inhaystack
size_tstartIdxindex of a well-formed code point inhaystack to start searching from; defaults to 0
CaseSensitivecsspecifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive)
Returns:
The index of the first character inhaystack that is not an element ofneedles. If all characters ofhaystack are elements ofneedles orstartIdx is greater than or equal tohaystack.length, then -1 is returned. If the parameters are not valid UTF, the result will still be either -1 or in the range [startIdx ..haystack.length], but will not be reliable otherwise.
Throws:
If the sequence starting atstartIdx does not represent a well-formed code point, then astd.utf.UTFException may be thrown.
Examples:
writeln(indexOfNeither("abba","a", 2));// 2writeln(indexOfNeither("def","de", 1));// 2writeln(indexOfNeither("dfefffg","dfe", 4));// 6
Examples:
writeln(indexOfNeither("def","a"));// 0writeln(indexOfNeither("def","de"));// 2writeln(indexOfNeither("dfefffg","dfe"));// 6
pure @safe ptrdiff_tlastIndexOfNeither(Char, Char2)(const(Char)[]haystack, const(Char2)[]needles, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char && isSomeChar!Char2);

pure @safe ptrdiff_tlastIndexOfNeither(Char, Char2)(const(Char)[]haystack, const(Char2)[]needles, in size_tstopIdx, in CaseSensitivecs = Yes.caseSensitive)
if (isSomeChar!Char && isSomeChar!Char2);
Searches for the last character inhaystack that is not inneedles.
Parameters:
const(Char)[]haystackstring to search for needles in
const(Char2)[]needlescharacters to search for inhaystack
size_tstopIdxindex inhaystack to stop searching at (exclusive); defaults tohaystack.length
CaseSensitivecsspecifies whether comparisons are case-sensitive (Yes.caseSensitive) or not (No.caseSensitive)
Returns:
The index of the last character inhaystack that is not an element ofneedles. If all characters ofhaystack are inneedles orstopIdx is 0, then -1 is returned. If the parameters are not valid UTF, the result will still be in the range [-1 ..stopIdx], but will not be reliable otherwise.
Examples:
writeln(lastIndexOfNeither("abba","a"));// 2writeln(lastIndexOfNeither("def","f"));// 1
Examples:
writeln(lastIndexOfNeither("def","rsa", 3));// -1writeln(lastIndexOfNeither("abba","a", 2));// 1
pure nothrow @nogc @safe autorepresentation(Char)(Char[]s)
if (isSomeChar!Char);
Returns the representation of a string, which has the same type as the string except the character type is replaced byubyte,ushort, oruint depending on the character width.
Parameters:
Char[]sThe string to return the representation of.
Returns:
The representation of the passed string.
Examples:
strings ="hello";staticassert(is(typeof(representation(s)) ==immutable(ubyte)[]));assert(representation(s)iscast(immutable(ubyte)[])s);writeln(representation(s));// [0x68, 0x65, 0x6c, 0x6c, 0x6f]
pure @trusted Scapitalize(S)(Sinput)
if (isSomeString!S);
Capitalize the first character ofs and convert the rest ofs to lowercase.
Parameters:
SinputThe string to capitalize.
Returns:
The capitalized string.
See Also:
std.uni.asCapitalized for a lazy range version that doesn't allocate memory
Examples:
writeln(capitalize("hello"));// "Hello"writeln(capitalize("World"));// "World"
aliasKeepTerminator = std.typecons.Flag!"keepTerminator".Flag;

pure @safe C[][]splitLines(C)(C[]s, KeepTerminatorkeepTerm = No.keepTerminator)
if (isSomeChar!C);
Splits into an array of lines according to the unicode standard using'\r','\n',"\r\n",std.uni.lineSep,std.uni.paraSep,U+0085 (NEL),'\v' and'\f' as delimiters. IfkeepTerm is set toKeepTerminator.yes, then the delimiter is included in the strings returned.
Does not throw on invalid UTF; such is simply passed unchanged to the output.
Allocates memory; uselineSplitter for an alternative that does not.
Adheres toUnicode 7.0.
Parameters:
C[]sa string ofchars,wchars, ordchars, or any custom type that casts to astring type
KeepTerminatorkeepTermwhether delimiter is included or not in the results
Returns:
array of strings, each element is a line that is a slice ofs
See Also:
Examples:
strings ="Hello\nmy\rname\nis";writeln(splitLines(s));// ["Hello", "my", "name", "is"]
autolineSplitter(KeepTerminator keepTerm = No.keepTerminator, Range)(Ranger)
if (hasSlicing!Range && hasLength!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range);

autolineSplitter(KeepTerminator keepTerm = No.keepTerminator, C)(C[]r)
if (isSomeChar!C);
Split an array or slicable range of characters into a range of lines using'\r','\n','\v','\f',"\r\n",std.uni.lineSep,std.uni.paraSep and'\u0085' (NEL) as delimiters. IfkeepTerm is set toYes.keepTerminator, then the delimiter is included in the slices returned.
Does not throw on invalid UTF; such is simply passed unchanged to the output.
Adheres toUnicode 7.0.
Does not allocate memory.
Parameters:
Rangerarray ofchars,wchars, ordchars or a slicable range
keepTermwhether delimiter is included or not in the results
Returns:
range of slices of the input ranger
See Also:
Examples:
import std.array : array;string s ="Hello\nmy\rname\nis";/* notice the call to 'array' to turn the lazy range created bylineSplitter comparable to the string[] created by splitLines.*/writeln(lineSplitter(s).array);// splitLines(s)
Examples:
auto s ="\rpeter\n\rpaul\r\njerry\u2028ice\u2029cream\n\nsunday\nmon\u2030day\n";auto lines = s.lineSplitter();staticimmutable witness = ["","peter","","paul","jerry","ice","cream","","sunday","mon\u2030day"];uint i;foreach (line; lines){    writeln(line);// witness[i++]}writeln(i);// witness.length
autostripLeft(Range)(Rangeinput)
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && !isInfinite!Range && !isConvertibleToString!Range);

autostripLeft(Range, Char)(Rangeinput, const(Char)[]chars)
if ((isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) || isConvertibleToString!Range) && isSomeChar!Char);
Strips leading whitespace (as defined bystd.uni.isWhite) or as specified in the second argument.
Parameters:
Rangeinputstring orforward range of characters
const(Char)[]charsstring of characters to be stripped
Returns:
input stripped of leading whitespace or characters specified in the second argument.

Postconditionsinput and the returned value will share the same tail (seestd.array.sameTail).

See Also:
Generic stripping on ranges:std.algorithm.mutation.stripLeft
Examples:
import std.uni : lineSep, paraSep;assert(stripLeft("     hello world     ") =="hello world     ");assert(stripLeft("\n\t\v\rhello world\n\t\v\r") =="hello world\n\t\v\r");assert(stripLeft(" \u2028hello world") =="hello world");assert(stripLeft("hello world") =="hello world");assert(stripLeft([lineSep] ~"hello world" ~ lineSep) =="hello world" ~ [lineSep]);assert(stripLeft([paraSep] ~"hello world" ~ paraSep) =="hello world" ~ [paraSep]);import std.array : array;import std.utf : byChar;assert(stripLeft("     hello world     "w.byChar).array =="hello world     ");assert(stripLeft("     \u2022hello world     ".byChar).array =="\u2022hello world     ");
Examples:
assert(stripLeft("     hello world     "," ") =="hello world     ");assert(stripLeft("xxxxxhello world     ","x") =="hello world     ");assert(stripLeft("xxxyy    hello world     ","xy ") =="hello world     ");
Examples:
import std.array : array;import std.utf : byChar, byWchar, byDchar;assert(stripLeft("  xxxyy hello world     "w.byChar,"xy ").array =="hello world     ");assert(stripLeft("\u2028\u2020hello world\u2028"w.byWchar,"\u2028").array =="\u2020hello world\u2028");assert(stripLeft("\U00010001hello world"w.byWchar," ").array =="\U00010001hello world"w);assert(stripLeft("\U00010001 xyhello world"d.byDchar,"\U00010001 xy").array =="hello world"d);writeln(stripLeft("\u2020hello"w,"\u2020"w));// "hello"wwriteln(stripLeft("\U00010001hello"d,"\U00010001"d));// "hello"dwriteln(stripLeft(" hello ",""));// " hello "
autostripRight(Range)(Rangestr)
if (isSomeString!Range || isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && !isConvertibleToString!Range && isSomeChar!(ElementEncodingType!Range));

autostripRight(Range, Char)(Rangestr, const(Char)[]chars)
if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isConvertibleToString!Range) && isSomeChar!Char);
Strips trailing whitespace (as defined bystd.uni.isWhite) or as specified in the second argument.
Parameters:
Rangestrstring or random access range of characters
const(Char)[]charsstring of characters to be stripped
Returns:
slice ofstr stripped of trailing whitespace or characters specified in the second argument.
See Also:
Generic stripping on ranges:std.algorithm.mutation.stripRight
Examples:
import std.uni : lineSep, paraSep;assert(stripRight("     hello world     ") =="     hello world");assert(stripRight("\n\t\v\rhello world\n\t\v\r") =="\n\t\v\rhello world");assert(stripRight("hello world") =="hello world");assert(stripRight([lineSep] ~"hello world" ~ lineSep) ==       [lineSep] ~"hello world");assert(stripRight([paraSep] ~"hello world" ~ paraSep) ==       [paraSep] ~"hello world");
Examples:
assert(stripRight("     hello world     ","x") =="     hello world     ");assert(stripRight("     hello world     "," ") =="     hello world");assert(stripRight("     hello worldxy     ","xy ") =="     hello world");
autostrip(Range)(Rangestr)
if (isSomeString!Range || isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && !isConvertibleToString!Range && isSomeChar!(ElementEncodingType!Range));

autostrip(Range, Char)(Rangestr, const(Char)[]chars)
if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isConvertibleToString!Range) && isSomeChar!Char);

autostrip(Range, Char)(Rangestr, const(Char)[]leftChars, const(Char)[]rightChars)
if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isConvertibleToString!Range) && isSomeChar!Char);
Strips both leading and trailing whitespace (as defined bystd.uni.isWhite) or as specified in the second argument.
Parameters:
Rangestrstring or random access range of characters
const(Char)[]charsstring of characters to be stripped
const(Char)[]leftCharsstring of leading characters to be stripped
const(Char)[]rightCharsstring of trailing characters to be stripped
Returns:
slice ofstr stripped of leading and trailing whitespace or characters as specified in the second argument.
See Also:
Generic stripping on ranges:std.algorithm.mutation.strip
Examples:
import std.uni : lineSep, paraSep;assert(strip("     hello world     ") =="hello world");assert(strip("\n\t\v\rhello world\n\t\v\r") =="hello world");assert(strip("hello world") =="hello world");assert(strip([lineSep] ~"hello world" ~ [lineSep]) =="hello world");assert(strip([paraSep] ~"hello world" ~ [paraSep]) =="hello world");
Examples:
assert(strip("     hello world     ","x") =="     hello world     ");assert(strip("     hello world     "," ") =="hello world");assert(strip("   xyxyhello worldxyxy     ","xy ") =="hello world");writeln(strip("\u2020hello\u2020"w,"\u2020"w));// "hello"wwriteln(strip("\U00010001hello\U00010001"d,"\U00010001"d));// "hello"dwriteln(strip(" hello ",""));// " hello "
Examples:
writeln(strip("xxhelloyy","x","y"));// "hello"assert(strip("   xyxyhello worldxyxyzz    ","xy ","xyz ") =="hello world");writeln(strip("\u2020hello\u2028"w,"\u2020"w,"\u2028"w));// "hello"wassert(strip("\U00010001hello\U00010002"d,"\U00010001"d,"\U00010002"d) =="hello"d);writeln(strip(" hello ","",""));// " hello "
Rangechomp(Range)(Rangestr)
if ((isRandomAccessRange!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range);

Rangechomp(Range, C2)(Rangestr, const(C2)[]delimiter)
if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range && isSomeChar!C2);
Ifstr ends withdelimiter, thenstr is returned withoutdelimiter on its end. If itstr doesnot end withdelimiter, then it is returned unchanged.
If nodelimiter is given, then one trailing'\r','\n',"\r\n",'\f','\v',std.uni.lineSep,std.uni.paraSep, orstd.uni.nelSep is removed from the end ofstr. Ifstr does not end with any of those characters, then it is returned unchanged.
Parameters:
Rangestrstring or indexable range of characters
const(C2)[]delimiterstring of characters to be sliced off end of str[]
Returns:
slice of str
Examples:
import std.uni : lineSep, paraSep, nelSep;import std.utf : decode;writeln(chomp(" hello world  \n\r"));// " hello world  \n"writeln(chomp(" hello world  \r\n"));// " hello world  "writeln(chomp(" hello world  \f"));// " hello world  "writeln(chomp(" hello world  \v"));// " hello world  "writeln(chomp(" hello world  \n\n"));// " hello world  \n"writeln(chomp(" hello world  \n\n "));// " hello world  \n\n "writeln(chomp(" hello world  \n\n" ~ [lineSep]));// " hello world  \n\n"writeln(chomp(" hello world  \n\n" ~ [paraSep]));// " hello world  \n\n"writeln(chomp(" hello world  \n\n" ~ [nelSep]));// " hello world  \n\n"writeln(chomp(" hello world "));// " hello world "writeln(chomp(" hello world"));// " hello world"writeln(chomp(""));// ""writeln(chomp(" hello world","orld"));// " hello w"writeln(chomp(" hello world"," he"));// " hello world"writeln(chomp("","hello"));// ""// Don't decode pointlesslywriteln(chomp("hello\xFE","\r"));// "hello\xFE"
RangechompPrefix(Range, C2)(Rangestr, const(C2)[]delimiter)
if ((isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range && isSomeChar!C2);
Ifstr starts withdelimiter, then the part ofstr followingdelimiter is returned. Ifstr doesnot start with
delimiter, then it is returned unchanged.
Parameters:
Rangestrstring orforward range of characters
const(C2)[]delimiterstring of characters to be sliced off front of str[]
Returns:
slice of str
Examples:
writeln(chompPrefix("hello world","he"));// "llo world"writeln(chompPrefix("hello world","hello w"));// "orld"writeln(chompPrefix("hello world"," world"));// "hello world"writeln(chompPrefix("","hello"));// ""
Rangechop(Range)(Rangestr)
if ((isBidirectionalRange!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range);
Returnsstr without its last character, if there is one. Ifstr ends with"\r\n", then both are removed. Ifstr is empty, then it is returned unchanged.
Parameters:
Rangestrstring (must be valid UTF)
Returns:
slice of str
Examples:
writeln(chop("hello world"));// "hello worl"writeln(chop("hello world\n"));// "hello world"writeln(chop("hello world\r"));// "hello world"writeln(chop("hello world\n\r"));// "hello world\n"writeln(chop("hello world\r\n"));// "hello world"writeln(chop("Walter Bright"));// "Walter Brigh"writeln(chop(""));// ""
SleftJustify(S)(Ss, size_twidth, dcharfillChar = ' ')
if (isSomeString!S);
Left justifys in a fieldwidth characters wide.fillChar is the character that will be used to fill up the space in the field thats doesn't fill.
Parameters:
Ssstring
size_twidthminimum field width
dcharfillCharused to pad end up towidth characters
Returns:
GC allocated string
See Also:
leftJustifier, which does not allocate
Examples:
writeln(leftJustify("hello", 7, 'X'));// "helloXX"writeln(leftJustify("hello", 2, 'X'));// "hello"writeln(leftJustify("hello", 9, 'X'));// "helloXXXX"
autoleftJustifier(Range)(Ranger, size_twidth, dcharfillChar = ' ')
if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range);
Left justifys in a fieldwidth characters wide.fillChar is the character that will be used to fill up the space in the field thats doesn't fill.
Parameters:
Rangerstring or range of characters
size_twidthminimum field width
dcharfillCharused to pad end up towidth characters
Returns:
a lazy range of the left justified result
See Also:
Examples:
import std.algorithm.comparison : equal;import std.utf : byChar;assert(leftJustifier("hello", 2).equal("hello".byChar));assert(leftJustifier("hello", 7).equal("hello  ".byChar));assert(leftJustifier("hello", 7, 'x').equal("helloxx".byChar));
SrightJustify(S)(Ss, size_twidth, dcharfillChar = ' ')
if (isSomeString!S);
Right justifys in a fieldwidth characters wide.fillChar is the character that will be used to fill up the space in the field thats doesn't fill.
Parameters:
Ssstring
size_twidthminimum field width
dcharfillCharused to pad end up towidth characters
Returns:
GC allocated string
See Also:
rightJustifier, which does not allocate
Examples:
writeln(rightJustify("hello", 7, 'X'));// "XXhello"writeln(rightJustify("hello", 2, 'X'));// "hello"writeln(rightJustify("hello", 9, 'X'));// "XXXXhello"
autorightJustifier(Range)(Ranger, size_twidth, dcharfillChar = ' ')
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range);
Right justifys in a fieldwidth characters wide.fillChar is the character that will be used to fill up the space in the field thats doesn't fill.
Parameters:
Rangerstring orforward range of characters
size_twidthminimum field width
dcharfillCharused to pad end up towidth characters
Returns:
a lazy range of the right justified result
See Also:
Examples:
import std.algorithm.comparison : equal;import std.utf : byChar;assert(rightJustifier("hello", 2).equal("hello".byChar));assert(rightJustifier("hello", 7).equal("  hello".byChar));assert(rightJustifier("hello", 7, 'x').equal("xxhello".byChar));
Scenter(S)(Ss, size_twidth, dcharfillChar = ' ')
if (isSomeString!S);
Centers in a fieldwidth characters wide.fillChar is the character that will be used to fill up the space in the field thats doesn't fill.
Parameters:
SsThe string to center
size_twidthWidth of the field to centers in
dcharfillCharThe character to use for filling excess space in the field
Returns:
The resulting center-justified string. The returned string is GC-allocated. To avoid GC allocation, usecenterJustifier instead.
Examples:
writeln(center("hello", 7, 'X'));// "XhelloX"writeln(center("hello", 2, 'X'));// "hello"writeln(center("hello", 9, 'X'));// "XXhelloXX"
autocenterJustifier(Range)(Ranger, size_twidth, dcharfillChar = ' ')
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range);
Center justifyr in a fieldwidth characters wide.fillChar is the character that will be used to fill up the space in the field thatr doesn't fill.
Parameters:
Rangerstring orforward range of characters
size_twidthminimum field width
dcharfillCharused to pad end up towidth characters
Returns:
a lazy range of the center justified result
See Also:
Examples:
import std.algorithm.comparison : equal;import std.utf : byChar;assert(centerJustifier("hello", 2).equal("hello".byChar));assert(centerJustifier("hello", 8).equal(" hello  ".byChar));assert(centerJustifier("hello", 7, 'x').equal("xhellox".byChar));
pure autodetab(Range)(auto ref Ranges, size_ttabSize = 8)
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) || __traits(compiles, StringTypeOf!Range));
Replace each tab character ins with the number of spaces necessary to align the following character at the next tab stop.
Parameters:
Rangesstring
size_ttabSizedistance between tab stops
Returns:
GC allocated string with tabs replaced with spaces
Examples:
writeln(detab(" \n\tx", 9));// " \n         x"
autodetabber(Range)(Ranger, size_ttabSize = 8)
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range);

autodetabber(Range)(auto ref Ranger, size_ttabSize = 8)
if (isConvertibleToString!Range);
Replace each tab character inr with the number of spaces necessary to align the following character at the next tab stop.
Parameters:
Rangerstring orforward range
size_ttabSizedistance between tab stops
Returns:
lazy forward range with tabs replaced with spaces
Examples:
import std.array : array;writeln(detabber(" \n\tx", 9).array);// " \n         x"
Examples:
import std.array : array;import std.utf : byChar, byWchar;writeln(detabber(" \u2029\t".byChar, 9).array);// " \u2029         "autor ="hel\tx".byWchar.detabber();writeln(r.front);// 'h'auto s =r.save;r.popFront();r.popFront();writeln(r.front);// 'l'writeln(s.front);// 'h'
autoentab(Range)(Ranges, size_ttabSize = 8)
if (isForwardRange!Range && isSomeChar!(ElementEncodingType!Range));
Replaces spaces ins with the optimal number of tabs. All spaces and tabs at the end of a line are removed.
Parameters:
RangesString to convert.
size_ttabSizeTab columns aretabSize spaces apart.
Returns:
GC allocated string with spaces replaced with tabs; useentabber to not allocate.
See Also:
Examples:
writeln(entab("        x \n"));// "\tx\n"
autoentabber(Range)(Ranger, size_ttabSize = 8)
if (isForwardRange!Range && !isConvertibleToString!Range);
Replaces spaces in ranger with the optimal number of tabs. All spaces and tabs at the end of a line are removed.
Parameters:
Rangerstring orforward range
size_ttabSizedistance between tab stops
Returns:
lazy forward range with spaces replaced with tabs
See Also:
Examples:
import std.array : array;writeln(entabber("        x \n").array);// "\tx\n"
pure @safe C1[]translate(C1, C2 = immutable(char))(C1[]str, in dchar[dchar]transTable, const(C2)[]toRemove = null)
if (isSomeChar!C1 && isSomeChar!C2);

pure @safe C1[]translate(C1, S, C2 = immutable(char))(C1[]str, in S[dchar]transTable, const(C2)[]toRemove = null)
if (isSomeChar!C1 && isSomeString!S && isSomeChar!C2);
Replaces the characters instr which are keys intransTable with their corresponding values intransTable.transTable is an AA where its keys aredchar and its values are eitherdchar or some type of string. Also, iftoRemove is given, the characters in it are removed fromstr prior to translation.str itself is unaltered. A copy with the changes is returned.
See Also:
Parameters:
C1[]strThe original string.
dchar[dchar]transTableThe AA indicating which characters to replace and what to replace them with.
const(C2)[]toRemoveThe characters to remove from the string.
Examples:
dchar[dchar] transTable1 = ['e' : '5', 'o' : '7', '5': 'q'];writeln(translate("hello world", transTable1));// "h5ll7 w7rld"writeln(translate("hello world", transTable1,"low"));// "h5 rd"string[dchar] transTable2 = ['e' :"5", 'o' :"orange"];writeln(translate("hello world", transTable2));// "h5llorange worangerld"
voidtranslate(C1, C2 = immutable(char), Buffer)(const(C1)[]str, in dchar[dchar]transTable, const(C2)[]toRemove, Bufferbuffer)
if (isSomeChar!C1 && isSomeChar!C2 && isOutputRange!(Buffer, C1));

voidtranslate(C1, S, C2 = immutable(char), Buffer)(C1[]str, in S[dchar]transTable, const(C2)[]toRemove, Bufferbuffer)
if (isSomeChar!C1 && isSomeString!S && isSomeChar!C2 && isOutputRange!(Buffer, S));
This is an overload oftranslate which takes an existing buffer to write the contents to.
Parameters:
const(C1)[]strThe original string.
dchar[dchar]transTableThe AA indicating which characters to replace and what to replace them with.
const(C2)[]toRemoveThe characters to remove from the string.
BufferbufferAn output range to write the contents to.
Examples:
import std.array : appender;dchar[dchar] transTable1 = ['e' : '5', 'o' : '7', '5': 'q'];autobuffer = appender!(dchar[])();translate("hello world", transTable1,null,buffer);writeln(buffer.data);// "h5ll7 w7rld"buffer.clear();translate("hello world", transTable1,"low",buffer);writeln(buffer.data);// "h5 rd"buffer.clear();string[dchar] transTable2 = ['e' :"5", 'o' :"orange"];translate("hello world", transTable2,null,buffer);writeln(buffer.data);// "h5llorange worangerld"
pure nothrow @trusted C[]translate(C = immutable(char))(scope const(char)[]str, scope const(char)[]transTable, scope const(char)[]toRemove = null)
if (is(immutable(C) == immutable(char)));
This is anASCII-only overload oftranslate. It willnot work with Unicode. It exists as an optimization for the cases where Unicode processing is not necessary.
Unlike the other overloads oftranslate, this one does not take an AA. Rather, it takes astring generated bymakeTransTable.
The array generated bymakeTransTable is256 elements long such that the index is equal to the ASCII character being replaced and the value is equal to the character that it's being replaced with. Note that translate does not decode any of the characters, so you can actually pass it Extended ASCII characters if you want to (ASCII only actually uses128 characters), but be warned that Extended ASCII characters are not valid Unicode and therefore will result in aUTFException being thrown from most other Phobos functions.
Also, because no decoding occurs, it is possible to use this overload to translate ASCII characters within a proper UTF-8 string without altering the other, non-ASCII characters. It's replacing any code unit greater than127 with another code unit or replacing any code unit with another code unit greater than127 which will cause UTF validation issues.
See Also:
Parameters:
const(char)[]strThe original string.
const(char)[]transTableThe string indicating which characters to replace and what to replace them with. It is generated bymakeTransTable.
const(char)[]toRemoveThe characters to remove from the string.
Examples:
auto transTable1 = makeTrans("eo5","57q");writeln(translate("hello world", transTable1));// "h5ll7 w7rld"writeln(translate("hello world", transTable1,"low"));// "h5 rd"
pure nothrow @trusted stringmakeTrans(scope const(char)[]from, scope const(char)[]to);
Do same thing asmakeTransTable but allocate the translation table on the GC heap.
UsemakeTransTable instead.
Examples:
auto transTable1 =makeTrans("eo5","57q");writeln(translate("hello world", transTable1));// "h5ll7 w7rld"writeln(translate("hello world", transTable1,"low"));// "h5 rd"
pure nothrow @nogc @safe char[256]makeTransTable(scope const(char)[]from, scope const(char)[]to);
Construct 256 character translation table, where characters in from[] are replaced by corresponding characters in to[].
Parameters:
const(char)[]fromarray of chars, less than or equal to 256 in length
const(char)[]tocorresponding array of chars to translate to
Returns:
translation array
Examples:
writeln(translate("hello world",makeTransTable("hl","q5")));// "qe55o wor5d"writeln(translate("hello world",makeTransTable("12345","67890")));// "hello world"
pure @trusted voidtranslate(C = immutable(char), Buffer)(scope const(char)[]str, scope const(char)[]transTable, scope const(char)[]toRemove, Bufferbuffer)
if (is(immutable(C) == immutable(char)) && isOutputRange!(Buffer, char));
This is anASCII-only overload oftranslate which takes an existing buffer to write the contents to.
Parameters:
const(char)[]strThe original string.
const(char)[]transTableThe string indicating which characters to replace and what to replace them with. It is generated bymakeTransTable.
const(char)[]toRemoveThe characters to remove from the string.
BufferbufferAn output range to write the contents to.
Examples:
import std.array : appender;autobuffer = appender!(char[])();auto transTable1 = makeTransTable("eo5","57q");translate("hello world", transTable1,null,buffer);writeln(buffer.data);// "h5ll7 w7rld"buffer.clear();translate("hello world", transTable1,"low",buffer);writeln(buffer.data);// "h5 rd"
pure @safe Ssucc(S)(Ss)
if (isSomeString!S);
Return string that is the 'successor' to s[]. If the rightmost character is a-zA-Z0-9, it is incremented within its case or digits. If it generates a carry, the process is repeated with the one to its immediate left.
Examples:
writeln(succ("1"));// "2"writeln(succ("9"));// "10"writeln(succ("999"));// "1000"writeln(succ("zz99"));// "aaa00"
C1[]tr(C1, C2, C3, C4 = immutable(char))(C1[]str, const(C2)[]from, const(C3)[]to, const(C4)[]modifiers = null);
Replaces the characters instr which are infrom with the the corresponding characters into and returns the resulting string.
tr is based onPosix's tr, though it doesn't do everything that the Posix utility does.
Parameters:
C1[]strThe original string.
const(C2)[]fromThe characters to replace.
const(C3)[]toThe characters to replace with.
const(C4)[]modifiersString containing modifiers.

Modifiers

ModifierDescription
'c'Complement the list of characters infrom
'd'Removes matching characters with no corresponding replacement into
's'Removes adjacent duplicates in the replaced characters
If the modifier'd' is present, then the number of characters into may be only0 or1.
If the modifier'd' isnot present, andto is empty, thento is taken to be the same asfrom.
If the modifier'd' isnot present, andto is shorter thanfrom, thento is extended by replicating the last character into.
Bothfrom andto may contain ranges using the'-' character (e.g."a-d" is synonymous with"abcd".) Neither accept a leading'^' as meaning the complement of the string (use the'c' modifier for that).

See Also:
Examples:
writeln(tr("abcdef","cd","CD"));// "abCDef"writeln(tr("1st March, 2018","March","MAR","s"));// "1st MAR, 2018"writeln(tr("abcdef","ef","","d"));// "abcd"writeln(tr("14-Jul-87","a-zA-Z"," ","cs"));// " Jul "
boolisNumeric(S)(Ss, boolbAllowSep = false)
if (isSomeString!S || isRandomAccessRange!S && hasSlicing!S && isSomeChar!(ElementType!S) && !isInfinite!S);
Takes a strings and determines if it represents a number. This function also takes an optional parameter,bAllowSep, which will accept the separator characters',' and'__' within the string. But these characters should be stripped from the string before using any of the conversion functions liketo!int(),to!float(), and etc else an error will occur.
Also please note, that no spaces are allowed within the string anywhere whether it's a leading, trailing, or embedded space(s), thus they too must be stripped from the string before using this function, or any of the conversion functions.
Parameters:
Ssthe string or random access range to check
boolbAllowSepaccept separator characters or not
Returns:
bool
Examples:
Integer Whole Number: (byte, ubyte, short, ushort, int, uint, long, and ulong) ['+'|'-']digit(s)[U|L|UL]
assert(isNumeric("123"));assert(isNumeric("123UL"));assert(isNumeric("123L"));assert(isNumeric("+123U"));assert(isNumeric("-123L"));
Examples:
Floating-Point Number: (float, double, real, ifloat, idouble, and ireal) ['+'|'-']digit(s)[.][digit(s)][[e-|e+]digit(s)][i|f|L|Li|fi]] or [nan|nani|inf|-inf]
assert(isNumeric("+123"));assert(isNumeric("-123.01"));assert(isNumeric("123.3e-10f"));assert(isNumeric("123.3e-10fi"));assert(isNumeric("123.3e-10L"));assert(isNumeric("nan"));assert(isNumeric("nani"));assert(isNumeric("-inf"));
Examples:
Floating-Point Number: (cfloat, cdouble, and creal) ['+'|'-']digit(s)[.][digit(s)][[e-|e+]digit(s)][+] [digit(s)[.][digit(s)][[e-|e+]digit(s)][i|f|L|Li|fi]] or [nan|nani|nan+nani|inf|-inf]
assert(isNumeric("-123e-1+456.9e-10Li"));assert(isNumeric("+123e+10+456i"));assert(isNumeric("123+456"));
Examples:
isNumeric works with CTFE
enum a =isNumeric("123.00E-5+1234.45E-12Li");enum b =isNumeric("12345xxxx890");staticassert( a);staticassert(!b);
char[4]soundexer(Range)(Rangestr)
if (isInputRange!Range && isSomeChar!(ElementEncodingType!Range) && !isConvertibleToString!Range);

char[4]soundexer(Range)(auto ref Rangestr)
if (isConvertibleToString!Range);
Soundex algorithm.
The Soundex algorithm converts a word into 4 characters based on how the word sounds phonetically. The idea is that two spellings that sound alike will have the same Soundex value, which means that Soundex can be used for fuzzy matching of names.
Parameters:
RangestrString or InputRange to convert to Soundex representation.
Returns:
The four character array with the Soundex result in it. The array has zero's in it if there is no Soundex representation for the string.
See Also:

NoteOnly works well with English names.

Examples:
writeln(soundexer("Gauss"));// "G200"writeln(soundexer("Ghosh"));// "G200"writeln(soundexer("Robert"));// "R163"writeln(soundexer("Rupert"));// "R163"writeln(soundexer("0123^&^^**&^"));// ['\0', '\0', '\0', '\0']
pure nothrow @safe char[]soundex(scope const(char)[]str, return scope char[]buffer = null);
Likesoundexer, but with different parameters and return value.
Parameters:
const(char)[]strString to convert to Soundex representation.
char[]bufferOptional 4 char array to put the resulting Soundex characters into. If null, the return value buffer will be allocated on the heap.
Returns:
The four character array with the Soundex result in it. Returns null if there is no Soundex representation for the string.
See Also:
Examples:
writeln(soundex("Gauss"));// "G200"writeln(soundex("Ghosh"));// "G200"writeln(soundex("Robert"));// "R163"writeln(soundex("Rupert"));// "R163"writeln(soundex("0123^&^^**&^"));// null
pure @safe string[string]abbrev(string[]values);
Construct an associative array consisting of all abbreviations that uniquely map to the strings in values.
This is useful in cases where the user is expected to type in one of a known set of strings, and the program will helpfully auto-complete the string once sufficient characters have been entered that uniquely identify it.
Examples:
import std.string;static string[] list = ["food","foxy" ];auto abbrevs =abbrev(list);assert(abbrevs == ["fox":"foxy","food":"food","foxy":"foxy","foo":"food"]);
size_tcolumn(Range)(Rangestr, in size_ttabsize = 8)
if ((isInputRange!Range && isSomeChar!(ElementEncodingType!Range) || isNarrowString!Range) && !isConvertibleToString!Range);
Compute column number at the end of the printed form of the string, assuming the string starts in the leftmost column, which is numbered starting from 0.
Tab characters are expanded into enough spaces to bring the column number to the next multiple of tabsize. If there are multiple lines in the string, the column number of the last line is returned.
Parameters:
Rangestrstring or InputRange to be analyzed
size_ttabsizenumber of columns a tab character represents
Returns:
column number
Examples:
import std.utf : byChar, byWchar, byDchar;writeln(column("1234 "));// 5writeln(column("1234 "w));// 5writeln(column("1234 "d));// 5writeln(column("1234 ".byChar()));// 5writeln(column("1234 "w.byWchar()));// 5writeln(column("1234 "d.byDchar()));// 5// Tab stops are set at 8 spaces by default; tab characters insert enough// spaces to bring the column position to the next multiple of 8.writeln(column("\t"));// 8writeln(column("1\t"));// 8writeln(column("\t1"));// 9writeln(column("123\t"));// 8// Other tab widths are possible by specifying it explicitly:writeln(column("\t", 4));// 4writeln(column("1\t", 4));// 4writeln(column("\t1", 4));// 5writeln(column("123\t", 4));// 4// New lines reset the column number.writeln(column("abc\n"));// 0writeln(column("abc\n1"));// 1writeln(column("abcdefg\r1234"));// 4writeln(column("abc\u20281"));// 1writeln(column("abc\u20291"));// 1writeln(column("abc\u00851"));// 1writeln(column("abc\u00861"));// 5
Swrap(S)(Ss, in size_tcolumns = 80, Sfirstindent = null, Sindent = null, in size_ttabsize = 8)
if (isSomeString!S);
Wrap text into a paragraph.
The input text string s is formed into a paragraph by breaking it up into a sequence of lines, delineated by \n, such that the number of columns is not exceeded on each line. The last line is terminated with a \n.
Parameters:
Sstext string to be wrapped
size_tcolumnsmaximum number of columns in the paragraph
Sfirstindentstring used to indent first line of the paragraph
Sindentstring to use to indent following lines of the paragraph
size_ttabsizecolumn spacing of tabs in firstindent[] and indent[]
Returns:
resulting paragraph as an allocated string
Bugs:
Columns are counted as the number of code points in the string. This may not correspond with the actual number of columns displayed if the string contains combining characters, modifiers, zero-width characters, or double-width characters.
Examples:
writeln(wrap("a short string", 7));// "a short\nstring\n"// wrap will not break inside of a word, but at the next spacewriteln(wrap("a short string", 4));// "a\nshort\nstring\n"writeln(wrap("a short string", 7,"\t"));// "\ta\nshort\nstring\n"writeln(wrap("a short string", 7,"\t","    "));// "\ta\n    short\n    string\n"
pure @safe Soutdent(S)(Sstr)
if (isSomeString!S);
Removes one level of indentation from a multi-line string.
This uniformly outdents the text as much as possible. Whitespace-only lines are always converted to blank lines.
Does not allocate memory if it does not throw.
Parameters:
Sstrmulti-line string
Returns:
outdented string
Throws:
StringException if indentation is done with different sequences of whitespace characters.
Examples:
enum pretty =q{   import std.stdio;   void main() {       writeln("Hello");   }}.outdent();enum ugly =q{import std.stdio;void main() {writeln("Hello");}};writeln(pretty);// ugly
pure @safe S[]outdent(S)(return scope S[]lines)
if (isSomeString!S);
Removes one level of indentation from an array of single-line strings.
This uniformly outdents the text as much as possible. Whitespace-only lines are always converted to blank lines.
Parameters:
S[]linesarray of single-line strings
Returns:
lines[] is rewritten in place with outdented lines
Throws:
StringException if indentation is done with different sequences of whitespace characters.
Examples:
auto str1 = ["    void main()\n","    {\n","        test();\n","    }\n"];auto str1Expected = ["void main()\n","{\n","    test();\n","}\n"];writeln(str1.outdent);// str1Expectedauto str2 = ["void main()\n","    {\n","            test();\n","    }\n"];writeln(str2.outdent);// str2
autoassumeUTF(T)(T[]arr)
if (staticIndexOf!(immutable(T), immutable(ubyte), immutable(ushort), immutable(uint)) != -1);
Assume the given array of integersarr is a well-formed UTF string andreturn it typed as a UTF string.
ubyte becomeschar,ushort becomeswchar anduintbecomesdchar. Type qualifiers are preserved.
When compiled with debug mode, this function performs an extra check to makesure the return value is a valid Unicode string.
Parameters:
T[]arrarray of bytes, ubytes, shorts, ushorts, ints, or uints
Returns:
arr retyped as an array of chars, wchars, or dchars
Throws:
In debug modeAssertError, when the result is not a well-formed UTF string.
See Also:
Examples:
string a ="Hölo World";immutable(ubyte)[] b = a.representation;string c = b.assumeUTF;writeln(c);// "Hölo World"
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Sat Feb 21 04:08:08 2026

[8]ページ先頭

©2009-2026 Movatter.jp