ecere/gui/Window: Prevent uninitialized values if base Window methods not overridden...
[sdk] / extras / stringTools.ec
1 #ifdef ECERE_STATIC
2 public import static "ecere"
3 #else
4 public import "ecere"
5 #endif
6
7 public enum Trim { no, left = 1, right = 2, ends = 3, middle = 4, all = 7 };
8
9 void TrimChars(const char * string, char * output, const char * chars, Trim trim, bool squash, char alt)
10 {
11    const char * s = string;
12    char * o = output;
13    char ch;
14    bool keepChar = (trim & left) != left;
15    bool keepMiddleChars = (trim & middle) != middle;
16    for(; (ch = *s); s++)
17    {
18       if(strchr(chars, ch))
19       {
20          if(keepChar)
21          {
22             *o++ = alt;
23             if(squash)
24                keepChar = false;
25          }
26       }
27       else
28       {
29          if(!keepChar && keepMiddleChars)
30             keepChar = true;
31          *o++ = ch;
32       }
33    }
34    if(keepMiddleChars && (trim & right) == right && o > output && *(o-1) == alt)
35       o--;
36    *o = '\0';
37 }
38
39 char * TrimCharsCopy(const char * string, const char * chars, Trim trim, bool squash, char alt)
40 {
41    int len = strlen(string);
42    char * output = new char[len+1];
43    TrimChars(string, output, chars, trim, squash, alt);
44    len = strlen(output);
45    output = renew output char[len+1];
46    return output;
47 }
48
49 void TrimTestChars(const char * string, char * output, int (*CharTest)(char), Trim trim, bool squash, char alt)
50 {
51    const char * s = string;
52    char * o = output;
53    char ch;
54    bool keepChar = (trim & left) != left;
55    bool keepMiddleChars = (trim & middle) != middle;
56    for(; (ch = *s); s++)
57    {
58       if(CharTest(ch))
59       {
60          if(keepChar)
61          {
62             *o++ = alt;
63             if(squash)
64                keepChar = false;
65          }
66       }
67       else
68       {
69          if(!keepChar && keepMiddleChars)
70             keepChar = true;
71          *o++ = ch;
72       }
73    }
74    if(keepMiddleChars && (trim & right) == right && o > output && *(o-1) == alt)
75       o--;
76    *o = '\0';
77 }
78
79 char * TrimTestCharsCopy(const char * string, int (*CharTest)(char), Trim trim, bool squash, char alt)
80 {
81    int len = strlen(string);
82    char * output = new char[len+1];
83    TrimTestChars(string, output, CharTest, trim, squash, alt);
84    len = strlen(output);
85    output = renew output char[len+1];
86    return output;
87 }