PageRenderTime 29ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/Microsoft.Scripting/Utils/StringUtils.cs

http://ironlua.googlecode.com/
C# | 304 lines | 232 code | 51 blank | 21 comment | 68 complexity | 709c1c220ab884b93529f513dc35e735 MD5 | raw file
  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Microsoft Corporation.
  4. *
  5. * This source code is subject to terms and conditions of the Microsoft Public License. A
  6. * copy of the license can be found in the License.html file at the root of this distribution. If
  7. * you cannot locate the Microsoft Public License, please send an email to
  8. * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. * by the terms of the Microsoft Public License.
  10. *
  11. * You must not remove this notice, or any other, from this software.
  12. *
  13. *
  14. * ***************************************************************************/
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Text;
  18. using System.Globalization;
  19. namespace Microsoft.Scripting.Utils {
  20. public static class StringUtils {
  21. public static Encoding DefaultEncoding {
  22. get {
  23. #if !SILVERLIGHT
  24. return Encoding.Default;
  25. #else
  26. return Encoding.UTF8;
  27. #endif
  28. }
  29. }
  30. public static string GetSuffix(string str, char separator, bool includeSeparator) {
  31. Contract.RequiresNotNull(str, "str");
  32. int last = str.LastIndexOf(separator);
  33. return (last != -1) ? str.Substring(includeSeparator ? last : last + 1) : null;
  34. }
  35. public static string GetLongestPrefix(string str, char separator, bool includeSeparator) {
  36. Contract.RequiresNotNull(str, "str");
  37. int last = str.LastIndexOf(separator);
  38. return (last != -1) ? str.Substring(0, (includeSeparator || last == 0) ? last : last - 1) : null;
  39. }
  40. public static int CountOf(string str, char c) {
  41. if (System.String.IsNullOrEmpty(str)) return 0;
  42. int result = 0;
  43. for (int i = 0; i < str.Length; i++) {
  44. if (c == str[i]) {
  45. result++;
  46. }
  47. }
  48. return result;
  49. }
  50. public static string[] Split(string str, string separator, int maxComponents, StringSplitOptions options) {
  51. Contract.RequiresNotNull(str, "str");
  52. #if SILVERLIGHT
  53. if (string.IsNullOrEmpty(separator)) throw new ArgumentNullException("separator");
  54. bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;
  55. List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);
  56. int i = 0;
  57. int next;
  58. while (maxComponents > 1 && i < str.Length && (next = str.IndexOf(separator, i)) != -1) {
  59. if (next > i || keep_empty) {
  60. result.Add(str.Substring(i, next - i));
  61. maxComponents--;
  62. }
  63. i = next + separator.Length;
  64. }
  65. if (i < str.Length || keep_empty) {
  66. result.Add(str.Substring(i));
  67. }
  68. return result.ToArray();
  69. #else
  70. return str.Split(new string[] { separator }, maxComponents, options);
  71. #endif
  72. }
  73. public static string[] Split(string str, char[] separators, int maxComponents, StringSplitOptions options) {
  74. Contract.RequiresNotNull(str, "str");
  75. #if SILVERLIGHT
  76. if (separators == null) return SplitOnWhiteSpace(str, maxComponents, options);
  77. bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;
  78. List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);
  79. int i = 0;
  80. int next;
  81. while (maxComponents > 1 && i < str.Length && (next = str.IndexOfAny(separators, i)) != -1) {
  82. if (next > i || keep_empty) {
  83. result.Add(str.Substring(i, next - i));
  84. maxComponents--;
  85. }
  86. i = next + 1;
  87. }
  88. if (i < str.Length || keep_empty) {
  89. result.Add(str.Substring(i));
  90. }
  91. return result.ToArray();
  92. #else
  93. return str.Split(separators, maxComponents, options);
  94. #endif
  95. }
  96. #if SILVERLIGHT
  97. public static string[] SplitOnWhiteSpace(string str, int maxComponents, StringSplitOptions options) {
  98. Contract.RequiresNotNull(str, "str");
  99. bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;
  100. List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);
  101. int i = 0;
  102. int next;
  103. while (maxComponents > 1 && i < str.Length && (next = IndexOfWhiteSpace(str, i)) != -1) {
  104. if (next > i || keep_empty) {
  105. result.Add(str.Substring(i, next - i));
  106. maxComponents--;
  107. }
  108. i = next + 1;
  109. }
  110. if (i < str.Length || keep_empty) {
  111. result.Add(str.Substring(i));
  112. }
  113. return result.ToArray();
  114. }
  115. public static int IndexOfWhiteSpace(string str, int start) {
  116. Contract.RequiresNotNull(str, "str");
  117. if (start < 0 || start > str.Length) throw new ArgumentOutOfRangeException("start");
  118. while (start < str.Length && !Char.IsWhiteSpace(str[start])) start++;
  119. return (start == str.Length) ? -1 : start;
  120. }
  121. #endif
  122. /// <summary>
  123. /// Splits text and optionally indents first lines - breaks along words, not characters.
  124. /// </summary>
  125. public static string SplitWords(string text, bool indentFirst, int lineWidth) {
  126. Contract.RequiresNotNull(text, "text");
  127. const string indent = " ";
  128. if (text.Length <= lineWidth || lineWidth <= 0) {
  129. if (indentFirst) return indent + text;
  130. return text;
  131. }
  132. StringBuilder res = new StringBuilder();
  133. int start = 0, len = lineWidth;
  134. while (start != text.Length) {
  135. if (len >= lineWidth) {
  136. // find last space to break on
  137. while (len != 0 && !Char.IsWhiteSpace(text[start + len - 1]))
  138. len--;
  139. }
  140. if (res.Length != 0) res.Append(' ');
  141. if (indentFirst || res.Length != 0) res.Append(indent);
  142. if (len == 0) {
  143. int copying = System.Math.Min(lineWidth, text.Length - start);
  144. res.Append(text, start, copying);
  145. start += copying;
  146. } else {
  147. res.Append(text, start, len);
  148. start += len;
  149. }
  150. res.AppendLine();
  151. len = System.Math.Min(lineWidth, text.Length - start);
  152. }
  153. return res.ToString();
  154. }
  155. public static string AddSlashes(string str) {
  156. Contract.RequiresNotNull(str, "str");
  157. // TODO: optimize
  158. StringBuilder result = new StringBuilder(str.Length);
  159. for (int i = 0; i < str.Length; i++) {
  160. switch (str[i]) {
  161. case '\a': result.Append("\\a"); break;
  162. case '\b': result.Append("\\b"); break;
  163. case '\f': result.Append("\\f"); break;
  164. case '\n': result.Append("\\n"); break;
  165. case '\r': result.Append("\\r"); break;
  166. case '\t': result.Append("\\t"); break;
  167. case '\v': result.Append("\\v"); break;
  168. default: result.Append(str[i]); break;
  169. }
  170. }
  171. return result.ToString();
  172. }
  173. public static bool TryParseDouble(string s, NumberStyles style, IFormatProvider provider, out double result) {
  174. #if SILVERLIGHT // Double.TryParse
  175. try {
  176. result = Double.Parse(s, style, provider);
  177. return true;
  178. } catch {
  179. result = 0.0;
  180. return false;
  181. }
  182. #else
  183. return Double.TryParse(s, style, provider, out result);
  184. #endif
  185. }
  186. public static bool TryParseInt32(string s, out int result) {
  187. #if SILVERLIGHT // Int32.TryParse
  188. try {
  189. result = Int32.Parse(s);
  190. return true;
  191. } catch {
  192. result = 0;
  193. return false;
  194. }
  195. #else
  196. return Int32.TryParse(s, out result);
  197. #endif
  198. }
  199. public static bool TryParseDateTimeExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
  200. #if SILVERLIGHT // DateTime.ParseExact
  201. try {
  202. result = DateTime.ParseExact(s, format, provider, style);
  203. return true;
  204. } catch {
  205. result = DateTime.MinValue;
  206. return false;
  207. }
  208. #else
  209. return DateTime.TryParseExact(s, format, provider, style, out result);
  210. #endif
  211. }
  212. public static bool TryParseDate(string s, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
  213. #if SILVERLIGHT // DateTime.Parse
  214. try {
  215. result = DateTime.Parse(s, provider, style);
  216. return true;
  217. } catch {
  218. result = DateTime.MinValue;
  219. return false;
  220. }
  221. #else
  222. return DateTime.TryParse(s, provider, style, out result);
  223. #endif
  224. }
  225. #if SILVERLIGHT
  226. private static Dictionary<string, CultureInfo> _cultureInfoCache = new Dictionary<string, CultureInfo>();
  227. #endif
  228. // Aims to be equivalent to Culture.GetCultureInfo for Silverlight
  229. public static CultureInfo GetCultureInfo(string name) {
  230. #if SILVERLIGHT
  231. lock (_cultureInfoCache) {
  232. CultureInfo result;
  233. if (_cultureInfoCache.TryGetValue(name, out result)) {
  234. return result;
  235. }
  236. _cultureInfoCache[name] = result = new CultureInfo(name);
  237. return result;
  238. }
  239. #else
  240. return CultureInfo.GetCultureInfo(name);
  241. #endif
  242. }
  243. // Like string.Split, but enumerates
  244. public static IEnumerable<string> Split(string str, string sep) {
  245. int start = 0, end;
  246. while ((end = str.IndexOf(sep, start)) != -1) {
  247. yield return str.Substring(start, end - start);
  248. start = end + sep.Length;
  249. }
  250. yield return str.Substring(start);
  251. }
  252. }
  253. }