File: StringUtils.cs

package info (click to toggle)
dlr-languages 20090805%2Bgit.e6b28d27%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 51,484 kB
  • ctags: 59,257
  • sloc: cs: 298,829; ruby: 159,643; xml: 19,872; python: 2,820; yacc: 1,960; makefile: 96; sh: 65
file content (304 lines) | stat: -rw-r--r-- 10,794 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A 
 * copy of the license can be found in the License.html file at the root of this distribution. If 
 * you cannot locate the  Microsoft Public License, please send an email to 
 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Microsoft.Scripting.Utils {
    public static class StringUtils {

        public static Encoding DefaultEncoding {
            get {
#if !SILVERLIGHT
                return Encoding.Default;
#else
                return Encoding.UTF8;
#endif
            }
        }

        public static string GetSuffix(string str, char separator, bool includeSeparator) {
            ContractUtils.RequiresNotNull(str, "str");
            int last = str.LastIndexOf(separator);
            return (last != -1) ? str.Substring(includeSeparator ? last : last + 1) : null;
        }

        public static string GetLongestPrefix(string str, char separator, bool includeSeparator) {
            ContractUtils.RequiresNotNull(str, "str");
            int last = str.LastIndexOf(separator);
            return (last != -1) ? str.Substring(0, (includeSeparator || last == 0) ? last : last - 1) : null;
        }

        public static int CountOf(string str, char c) {
            if (System.String.IsNullOrEmpty(str)) return 0;

            int result = 0;
            for (int i = 0; i < str.Length; i++) {
                if (c == str[i]) {
                    result++;
                }
            }
            return result;
        }

        public static string[] Split(string str, string separator, int maxComponents, StringSplitOptions options) {
            ContractUtils.RequiresNotNull(str, "str");
#if SILVERLIGHT
            if (string.IsNullOrEmpty(separator)) throw new ArgumentNullException("separator");

            bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;

            List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);

            int i = 0;
            int next;
            while (maxComponents > 1 && i < str.Length && (next = str.IndexOf(separator, i)) != -1) {

                if (next > i || keep_empty) {
                    result.Add(str.Substring(i, next - i));
                    maxComponents--;
                }

                i = next + separator.Length;
            }

            if (i < str.Length || keep_empty) {
                result.Add(str.Substring(i));
            }

            return result.ToArray();
#else
            return str.Split(new string[] { separator }, maxComponents, options);
#endif
        }

        public static string[] Split(string str, char[] separators, int maxComponents, StringSplitOptions options) {
            ContractUtils.RequiresNotNull(str, "str");
#if SILVERLIGHT
            if (separators == null) return SplitOnWhiteSpace(str, maxComponents, options);

            bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;

            List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);

            int i = 0;
            int next;
            while (maxComponents > 1 && i < str.Length && (next = str.IndexOfAny(separators, i)) != -1) {

                if (next > i || keep_empty) {
                    result.Add(str.Substring(i, next - i));
                    maxComponents--;
                }

                i = next + 1;
            }

            if (i < str.Length || keep_empty) {
                result.Add(str.Substring(i));
            }

            return result.ToArray();
#else
            return str.Split(separators, maxComponents, options);
#endif
        }

#if SILVERLIGHT
        public static string[] SplitOnWhiteSpace(string str, int maxComponents, StringSplitOptions options) {
            ContractUtils.RequiresNotNull(str, "str");

            bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;

            List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);

            int i = 0;
            int next;
            while (maxComponents > 1 && i < str.Length && (next = IndexOfWhiteSpace(str, i)) != -1) {

                if (next > i || keep_empty) {
                    result.Add(str.Substring(i, next - i));
                    maxComponents--;
                }

                i = next + 1;
            }

            if (i < str.Length || keep_empty) {
                result.Add(str.Substring(i));
            }

            return result.ToArray();
        }

        public static int IndexOfWhiteSpace(string str, int start) {
            ContractUtils.RequiresNotNull(str, "str");
            if (start < 0 || start > str.Length) throw new ArgumentOutOfRangeException("start");

            while (start < str.Length && !Char.IsWhiteSpace(str[start])) start++;

            return (start == str.Length) ? -1 : start;
        }
#endif

        /// <summary>
        /// Splits text and optionally indents first lines - breaks along words, not characters.
        /// </summary>
        public static string SplitWords(string text, bool indentFirst, int lineWidth) {
            ContractUtils.RequiresNotNull(text, "text");

            const string indent = "    ";

            if (text.Length <= lineWidth || lineWidth <= 0) {
                if (indentFirst) return indent + text;
                return text;
            }

            StringBuilder res = new StringBuilder();
            int start = 0, len = lineWidth;
            while (start != text.Length) {
                if (len >= lineWidth) {
                    // find last space to break on
                    while (len != 0 && !Char.IsWhiteSpace(text[start + len - 1]))
                        len--;
                }

                if (res.Length != 0) res.Append(' ');
                if (indentFirst || res.Length != 0) res.Append(indent);

                if (len == 0) {
                    int copying = System.Math.Min(lineWidth, text.Length - start);
                    res.Append(text, start, copying);
                    start += copying;
                } else {
                    res.Append(text, start, len);
                    start += len;
                }
                res.AppendLine();
                len = System.Math.Min(lineWidth, text.Length - start);
            }
            return res.ToString();
        }

        public static string AddSlashes(string str) {
            ContractUtils.RequiresNotNull(str, "str");

            // TODO: optimize
            StringBuilder result = new StringBuilder(str.Length);
            for (int i = 0; i < str.Length; i++) {
                switch (str[i]) {
                    case '\a': result.Append("\\a"); break;
                    case '\b': result.Append("\\b"); break;
                    case '\f': result.Append("\\f"); break;
                    case '\n': result.Append("\\n"); break;
                    case '\r': result.Append("\\r"); break;
                    case '\t': result.Append("\\t"); break;
                    case '\v': result.Append("\\v"); break;
                    default: result.Append(str[i]); break;
                }
            }

            return result.ToString();
        }

        public static bool TryParseDouble(string s, NumberStyles style, IFormatProvider provider, out double result) {
#if SILVERLIGHT // Double.TryParse
            try {
                result = Double.Parse(s, style, provider);
                return true;
            } catch {
                result = 0.0;
                return false;
            }
#else
            return Double.TryParse(s, style, provider, out result);
#endif
        }

        public static bool TryParseInt32(string s, out int result) {
#if SILVERLIGHT // Int32.TryParse
            try {
                result = Int32.Parse(s);
                return true;
            } catch {
                result = 0;
                return false;
            }
#else
            return Int32.TryParse(s, out result);
#endif
        }

        public static bool TryParseDateTimeExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
#if SILVERLIGHT // DateTime.ParseExact
            try {
                result = DateTime.ParseExact(s, format, provider, style);
                return true;
            } catch {
                result = DateTime.MinValue;
                return false;
            }
#else
            return DateTime.TryParseExact(s, format, provider, style, out result);
#endif
        }

        public static bool TryParseDate(string s, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
#if SILVERLIGHT // DateTime.Parse
            try {
                result = DateTime.Parse(s, provider, style);
                return true;
            } catch {
                result = DateTime.MinValue;
                return false;
            }
#else
            return DateTime.TryParse(s, provider, style, out result);
#endif
        }

#if SILVERLIGHT
        private static Dictionary<string, CultureInfo> _cultureInfoCache = new Dictionary<string, CultureInfo>();
#endif

        // Aims to be equivalent to Culture.GetCultureInfo for Silverlight
        public static CultureInfo GetCultureInfo(string name) {
#if SILVERLIGHT
            lock (_cultureInfoCache) {
                CultureInfo result;
                if (_cultureInfoCache.TryGetValue(name, out result)) {
                    return result;
                }
                _cultureInfoCache[name] = result = new CultureInfo(name);
                return result;
            }
#else
            return CultureInfo.GetCultureInfo(name);
#endif
        }

        // Like string.Split, but enumerates
        public static IEnumerable<string> Split(string str, string sep) {
            int start = 0, end;
            while ((end = str.IndexOf(sep, start)) != -1) {
                yield return str.Substring(start, end - start);

                start = end + sep.Length;
            }
            yield return str.Substring(start);
        }
    }
}