root/trunk/meta/string.d

Revision 213, 1.7 kB (checked in by Don Clugston, 6 years ago)

Deleted some old workarounds that haven't been required since about DMD 0.145.

Line 
1 module meta.string;
2
3 // Returns str[] sans trailing delimiter[], if any.
4 // Unlike std.string.chomp, it removes all instances of the delimiter.
5 template chomp(char [] str, char delimiter)
6 {
7   static if (str.length==0) const char[] chomp=str;
8   else static if (str[str.length - 1]==delimiter)
9      const char [] chomp = chomp!( str[0..$-1], delimiter);
10   else const char [] chomp = str;
11 }
12
13 // int find!(char [] str, char c);
14 // Find first occurrence of c in string str.
15 //
16 // Returns:
17 //  Index in s where c is found, -1 if not found.
18 template find(char[] str, char c, int n=0)
19 {
20   static if (str.length==n) const int find = -1;
21   else static if( c==str[n]) const int find = n;
22   else const int find = find!(str, c, n + 1);
23 }
24
25 // int rfind!(char [] str, char c);
26 // Find last occurrence of c in string str.
27 //
28 // Returns:
29 //   Index in s where c is found, -1 if not found.
30 template rfind(char[] str, char c, int n = 0)
31 {
32   static if (str.length==n) const int rfind = -1;
33   else static if( c==str[str.length - n - 1]) const int rfind = str.length - n - 1;
34   else const int rfind = rfind!(str, c, n + 1);
35 }
36
37 //  char [] repeat!(char [] str, uint n)
38 //
39 // Return a string that consists of s[] repeated n times.
40 template repeat(char [] str, uint n)
41 {
42    static if (n==0) const char [] repeat="";
43    else static if (n==1) const char [] repeat = str;
44    else const char [] repeat = str ~ repeat!(str, n-1);
45 }
46
47
48 version(testmeta) {
49  static assert( 11 == find!("it's in there somewhere!", 'r'));
50  static assert( -1 == find!("but it's not in this one", 'q'));
51  static assert( -1 == rfind!("not in here either", 'z'));
52  static assert( 4 == rfind!("but this is ok", 't'));
53  static assert(repeat!("abc", 4) == "abcabcabcabc");
54 }
Note: See TracBrowser for help on using the browser.