1
2 module ws..string;
3
4 public import std.string;
5 import std.conv;
6
7 __gshared:
8
9 static dchar formatChar = '%';
10
11 string tostring(Args...)(Args args){
12 try {
13 static if(args.length > 0){
14 static if(is(typeof(args[0]) == string) && args.length >= 2){
15 if(args[0].find(formatChar) < args[0].length){
16 size_t i = args[0].find(formatChar);
17 return args[0][0..i] ~ to!string(args[1]) ~ tostring(args[0][i+1..$], args[2..$]);
18 }else
19 return args[0] ~ to!string(args[1]) ~ tostring(args[2..$]);
20 }else
21 return to!string(args[0]) ~ tostring(args[1..$]);
22 }else
23 return "";
24 }catch(Exception e){
25 return "tostring error\n" ~ e.toString();
26 }
27 }
28
29 size_t find(string s, string what, size_t start = 0){
30 size_t right = 0;
31 foreach(i, c; s){
32 if(c == what[right])
33 right++;
34 else
35 right = 0;
36 if(right == what.length)
37 return i - right + 1;
38 }
39 return s.length;
40 }
41
42 size_t find(string s, dchar what, size_t start = 0){
43 for(; start < s.length; start++)
44 if(s[start] == what)
45 return start;
46 return s.length;
47 }
48
49 unittest {
50 auto s = "hello there";
51 assert(s.find("there!") == s.length);
52 assert(s.find("there") == 6);
53 assert(s.find('r') == 9);
54 }
55
56 /*
57 size_t findLast(string s, string what, size_t start = 0){
58 size_t right = 0;
59 foreach_reverse(i, c; s){
60 if(c == what[$-right])
61 right++;
62 else
63 right = 0;
64 if(right == what.length)
65 return i - right + 1;
66 }
67 return s.length;
68 }
69 */
70
71 size_t findLast(string s, dchar what, size_t start = 0){
72 if(!start) start = s.length-1;
73 for(; start < s.length; start--)
74 if(s[start] == what)
75 return start;
76 return s.length;
77 }
78
79 unittest {
80 assert("hello there".findLast('l') == 3);
81 }
82
83 string[] split(string what, string splitter){
84 string[] v;
85 string tmp = what;
86 for(size_t i = tmp.find(splitter); i < tmp.length; i = tmp.find(splitter)){
87 v ~= tmp[0..i];
88 tmp = tmp[i+splitter.length..$];
89 }
90 if(tmp.length)
91 v ~= tmp;
92 return v;
93 }
94
95 string[] split(string what, dchar splitter){
96 string[] v;
97 size_t last = 0;
98 foreach(i, dchar c; what){
99 if(c == splitter){
100 v ~= what[last .. i];
101 last = i+1;
102 }
103 }
104 if(last < what.length)
105 v ~= what[last..$];
106 return v;
107 }
108
109
110 unittest {
111 assert("a b c d efg".split(" ") == ["a", "b", "c", "d", "efg"]);
112 }