D Programming Language 2.0

- Comments
- D
- Search
- Home

Last update Tue Oct 16 09:58:53 2007

# std.string

String handling functions.
To copy or not to copy? When a function takes a string as a parameter, and returns a string, is that string the same as the input string, modified in place, or is it a modified copy of the input string? The D array convention is "copy-on-write". This means that if no modifications are done, the original string (or slices of it) can be returned. If any modifications are done, the returned string is a copy.

typedef StringException;
  Thrown on errors in string functions.
invariant(char)[16u] hexdigits;
  0..9A..F
invariant(char)[10u] digits;
  0..9
invariant(char)[8u] octdigits;
  0..7
invariant(char)[26u] lowercase;
  a..z
invariant(char)[26u] uppercase;
  A..Z
invariant(char)[52u] letters;
  A..Za..z
invariant(char)[6u] whitespace;
  ASCII whitespace
const dchar LS;
  UTF line separator
const dchar PS;
  UTF paragraph separator
invariant(char)[2u] newline;
  Newline sequence for this system
bool iswhite(dchar c);
  Returns true if c is whitespace
long atoi(in invariant(char)[] s);
  Convert string to integer.
real atof(in invariant(char)[] s);
  Convert string to real.
int cmp(in const const char[] s1, in const const char[] s2);
int icmp(in const const char[] s1, in const const char[] s2);
  Compare two strings. cmp is case sensitive, icmp is case insensitive.
  Returns:

  < 0 | s1 < s2
  = 0 | s1 == s2
  > 0 | s1 > s2

char* toStringz(const(char)[] s);
  Convert array of chars s[] to a C-style 0 terminated string.
int find(in const const char[] s, dchar c);
int ifind(in const const char[] s, dchar c);
int rfind(in const const char[] s, dchar c);
int irfind(in const const char[] s, dchar c);
  find, ifind find first occurrence of c in string s. rfind, irfind find last occurrence of c in string s.
  find, rfind are case sensitive; ifind, irfind are case insensitive.
  Returns:
  Index in s where c is found, -1 if not found.
int find(in const const char[] s, in const const char[] sub);
int ifind(in const const char[] s, in const const char[] sub);
int rfind(in const const char[] s, in const const char[] sub);
int irfind(in const const char[] s, in const const char[] sub);
  find, ifind find first occurrence of sub[] in string s[]. rfind, irfind find last occurrence of sub[] in string s[].
  find, rfind are case sensitive; ifind, irfind are case insensitive.
  Returns:
  Index in s where c is found, -1 if not found.
invariant(char)[] tolower(invariant(char)[] s);
  Convert string s[] to lower case.
invariant(char)[] toupper(invariant(char)[] s);
  Convert string s[] to upper case.
invariant(char)[] capitalize(invariant(char)[] s);
  Capitalize first character of string s[], convert rest of string s[] to lower case.
invariant(char)[] capwords(invariant(char)[] s);
  Capitalize all words in string s[]. Remove leading and trailing whitespace. Replace all sequences of whitespace with a single space.
invariant(char)[] repeat(invariant(char)[] s, uint n);
  Return a string that consists of s[] repeated n times.
invariant(char)[] join(in const const char[][] words, in invariant(char)[] sep);
  Concatenate all the strings in words[] together into one string; use sep[] as the separator.
invariant(char)[][] split(invariant(char)[] s);
  Split s[] into an array of words, using whitespace as the delimiter.
invariant(char)[][] split(invariant(char)[] s, invariant(char)[] delim);
  Split s[] into an array of words, using delim[] as the delimiter.
invariant(char)[][] splitlines(invariant(char)[] s);
  Split s[] into an array of lines, using CR, LF, or CR-LF as the delimiter. The delimiter is not included in the line.
invariant(char)[] stripl(invariant(char)[] s);
invariant(char)[] stripr(invariant(char)[] s);
invariant(char)[] strip(invariant(char)[] s);
  Strips leading or trailing whitespace, or both.
C[] chomp(C)(C[] s, in C[] delimiter = null);
  Returns s[] sans trailing delimiter[], if any. If delimiter[] is null, removes trailing CR, LF, or CRLF, if any.
invariant(char)[] chop(invariant(char)[] s);
  Returns s[] sans trailing character, if there is one. If last two characters are CR-LF, then both are removed.
invariant(char)[] ljustify(invariant(char)[] s, int width);
invariant(char)[] rjustify(invariant(char)[] s, int width);
invariant(char)[] center(invariant(char)[] s, int width);
  Left justify, right justify, or center string s[] in field width chars wide.
invariant(char)[] zfill(invariant(char)[] s, int width);
  Same as rjustify(), but fill with '0's.
invariant(char)[] replace(invariant(char)[] s, invariant(char)[] from, invariant(char)[] to);
  Replace occurrences of from[] with to[] in s[].
invariant(char)[] replaceSlice(invariant(char)[] s, in invariant(char)[] slice, in invariant(char)[] replacement);
  Return a string that is s[] with slice[] replaced by replacement[].
invariant(char)[] insert(invariant(char)[] s, uint index, invariant(char)[] sub);
  Insert sub[] into s[] at location index.
uint count(invariant(char)[] s, invariant(char)[] sub);
  Count up all instances of sub[] in s[].
invariant(char)[] expandtabs(invariant(char)[] str, int tabsize = 8);
  Replace tabs with the appropriate number of spaces. tabsize is the distance between tab stops.
invariant(char)[] entab(invariant(char)[] s, int tabsize = 8);
  Replace spaces in string s with the optimal number of tabs. Trailing spaces or tabs in a line are removed.
  Params:

  invariant(char)[] s | String to convert.
  int tabsize | Tab columns are tabsize spaces apart. tabsize defaults to 8.

invariant(char)[] maketrans(in invariant(char)[] from, in invariant(char)[] to);
  Construct translation table for translate().
  BUG:
  only works with ASCII
invariant(char)[] translate(invariant(char)[] s, in invariant(char)[] transtab, in invariant(char)[] delchars);
  Translate characters in s[] using table created by maketrans(). Delete chars in delchars[].
  BUG:
  only works with ASCII
invariant(char)[] toString(bool b);
invariant(char)[] toString(char c);
invariant(char)[] toString(wchar c);
invariant(char)[] toString(dchar c);
invariant(char)[] toString(ubyte ub);
invariant(char)[] toString(ushort us);
invariant(char)[] toString(uint u);
invariant(char)[] toString(ulong u);
invariant(char)[] toString(byte b);
invariant(char)[] toString(short s);
invariant(char)[] toString(int i);
invariant(char)[] toString(long i);
invariant(char)[] toString(float f);
invariant(char)[] toString(double d);
invariant(char)[] toString(real r);
invariant(char)[] toString(ifloat f);
invariant(char)[] toString(idouble d);
invariant(char)[] toString(ireal r);
invariant(char)[] toString(cfloat f);
invariant(char)[] toString(cdouble d);
invariant(char)[] toString(creal r);
  Convert to string.
invariant(char)[] toString(long value, uint radix);
invariant(char)[] toString(ulong value, uint radix);
  Convert value to string in radix radix.
  radix must be a value from 2 to 36. value is treated as a signed value only if radix is 10. The characters A through Z are used to represent values 10 through 36.
invariant(char)[] toString(const const char* s);
  Convert C-style 0 terminated string s to string string.
invariant(char)[] format(...);
  Format arguments into a string.
char[] sformat(char[] s,...);
  Format arguments into string s which must be large enough to hold the result. Throws ArrayBoundsError if it is not.
  Returns:
  s
bool inPattern(dchar c, in invariant(char)[] pattern);
  See if character c is in the pattern.
  Patterns:
  A pattern is an array of characters much like a character class in regular expressions. A sequence of characters can be given, such as "abcde". The '-' can represent a range of characters, as "a-e" represents the same pattern as "abcde". "a-fA-F0-9" represents all the hex characters. If the first character of a pattern is '^', then the pattern is negated, i.e. "^0-9" means any character except a digit. The functions inPattern, countchars, removeschars, and squeeze use patterns.
  Note:
  In the future, the pattern syntax may be improved to be more like regular expression character classes.
int inPattern(dchar c, invariant(char)[][] patterns);
  See if character c is in the intersection of the patterns.
uint countchars(invariant(char)[] s, invariant(char)[] pattern);
  Count characters in s that match pattern.
invariant(char)[] removechars(invariant(char)[] s, in invariant(char)[] pattern);
  Return string that is s with all characters removed that match pattern.
invariant(char)[] squeeze(invariant(char)[] s, invariant(char)[] pattern = null);
  Return string where sequences of a character in s[] from pattern[] are replaced with a single instance of that character. If pattern is null, it defaults to all characters.
S munch(S)(ref S s, S pattern);
  Finds the position pos of the first character in s that does not match pattern (in the terminology used by inPattern). Updates s = s[pos..$]. Returns the slice from the beginning of the original (before update) string up to, and excluding, pos.
  Example:

      string s = "123abc";
      string t = munch(s, "0123456789");
      assert(t == "123" && s == "abc");
      t = munch(s, "0123456789");
      assert(t == "" && s == "abc");

  The munch function is mostly convenient for skipping certain category of characters (e.g. whitespace) when parsing strings. (In such cases, the return value is not used.)
invariant(char)[] succ(invariant(char)[] 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.
invariant(char)[] tr(invariant(char)[] str, invariant(char)[] from, invariant(char)[] to, invariant(char)[] modifiers = null);
  Replaces characters in str[] that are in from[] with corresponding characters in to[] and returns the resulting string.
  Params:

  invariant(char)[] modifiers | a string of modifier characters

  Modifiers:

  Modifier | Description
  --- | ---
  c | Complement the list of characters in from[]
  d | Removes matching characters with no corresponding replacement in to[]
  s | Removes adjacent duplicates in the replaced characters

  If modifier d is present, then the number of characters in to[] may be only 0 or 1.
  If modifier d is not present and to[] is null, then to[] is taken to be the same as from[].
  If modifier d is not present and to[] is shorter than from[], then to[] is extended by replicating the last character in to[].
  Both from[] and to[] may contain ranges using the - character, for example a-d is synonymous with abcd. Neither accept a leading ^ as meaning the complement of the string (use the c modifier for that).
final bool isNumeric(invariant(char)[] s, in const const bool bAllowSep = cast(const bool)false);
  [in] string s can be formatted in the following ways:
  Integer Whole Number: (for byte, ubyte, short, ushort, int, uint, long, and ulong) ['+'|'-']digit(s)[U|L|UL]
  Examples:
  123, 123UL, 123L, +123U, -123L
  Floating-Point Number: (for 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]
  Examples:
  +123., -123.01, 123.3e-10f, 123.3e-10fi, 123.3e-10L
  (for 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]
  Examples:
  nan, -123e-1+456.9e-10Li, +123e+10+456i, 123+456
  [in] bool bAllowSep False by default, but when set to true it 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 like toInt(), toFloat(), 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.
bool isNumeric(...);
  Allow any object as a parameter
bool isNumeric(TypeInfo[] _arguments, void* _argptr);
  Check only the first parameter, all others will be ignored.
char[] soundex(invariant(char)[] string, char[] buffer = null);
  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.
  Params:

  invariant(char)[] string | String to convert to Soundex representation.
  char[] buffer | Optional 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:
  Wikipedia, The Soundex Indexing System
  BUGS:
  Only works well with English names. There are other arguably better Soundex algorithms, but this one is the standard one.
invariant(char)[][invariant(char)[]] abbrev(invariant(char)[][] 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 autocomplete the string once sufficient characters have been entered that uniquely identify it.
  Example:

       import std.stdio;
       import std.string;

       void main()
       {
          static string[] list = [ "food", "foxy" ];

          auto abbrevs = std.string.abbrev(list);

          foreach (key, value; abbrevs)
          {
             writefln("%s => %s", key, value);
          }
       }

  produces the output:

       fox => foxy
       food => food
       foxy => foxy
       foo => food

uint column(invariant(char)[] str, int tabsize = 8);
  Compute column number after string if string starts in the leftmost column, which is numbered starting from 0.
invariant(char)[] wrap(invariant(char)[] s, int columns = 80, invariant(char)[] firstindent = null, invariant(char)[] indent = null, int tabsize = 8);
  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.
  Params:

  invariant(char)[] s | text string to be wrapped
  int columns | maximum number of columns in the paragraph
  invariant(char)[] firstindent | string used to indent first line of the paragraph
  invariant(char)[] indent | string to use to indent following lines of the paragraph
  int tabsize | column spacing of tabs

  Returns:
  The resulting paragraph.
invariant(char)[] isEmail(invariant(char)[] s);
  Does string s[] start with an email address?
  Returns:
  null it does not string it does, and this is the slice of s[] that is that email address
  References:
  RFC2822
invariant(char)[] isURL(invariant(char)[] s);
  Does string s[] start with a URL?
  Returns:
  null it does not string it does, and this is the slice of s[] that is that URL

Public Domain | Page generated by Ddoc.