comparison Chronosv2/source/Extensions/StringExtensions.cs @ 10:443821e55f06

Initial cleaned up add from Codeplex files
author stevenh7776 stevenhollidge@hotmail.com
date Tue, 21 Feb 2012 17:25:44 +0700
parents
children
comparison
equal deleted inserted replaced
9:904a9faadf8b 10:443821e55f06
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Text;
5 using System.Text.RegularExpressions;
6 using System.Xml;
7 using System.Xml.Linq;
8 using System.Xml.XPath;
9
10 namespace Chronos.Extensions
11 {
12 /// <summary>
13 /// Extension methods for the string data type
14 /// </summary>
15 public static class StringExtensions
16 {
17 #region · Extensions ·
18
19 #region · Common string extensions ·
20
21 /// <summary>
22 /// Determines whether the specified string is null or empty.
23 /// </summary>
24 /// <param name="value">The string value to check.</param>
25 public static bool IsEmpty(this string value)
26 {
27 return ((value == null) || (value.Length == 0));
28 }
29
30 /// <summary>
31 /// Determines whether the specified string is not null or empty.
32 /// </summary>
33 /// <param name="value">The string value to check.</param>
34 public static bool IsNotEmpty(this string value)
35 {
36 return (value.IsEmpty() == false);
37 }
38
39 /// <summary>
40 /// Checks whether the string is empty and returns a default value in case.
41 /// </summary>
42 /// <param name="value">The string to check.</param>
43 /// <param name="defaultValue">The default value.</param>
44 /// <returns>Either the string or the default value.</returns>
45 public static string IfEmpty(this string value, string defaultValue)
46 {
47 return (value.IsNotEmpty() ? value : defaultValue);
48 }
49
50 /// <summary>
51 /// Formats the value with the parameters using string.Format.
52 /// </summary>
53 /// <param name="value">The input string.</param>
54 /// <param name="parameters">The parameters.</param>
55 /// <returns></returns>
56 public static string FormatWith(this string value, params object[] parameters)
57 {
58 return string.Format(value, parameters);
59 }
60
61 /// <summary>
62 /// Trims the text to a provided maximum length.
63 /// </summary>
64 /// <param name="value">The input string.</param>
65 /// <param name="maxLength">Maximum length.</param>
66 /// <returns></returns>
67 /// <remarks>Proposed by Rene Schulte</remarks>
68 public static string TrimToMaxLength(this string value, int maxLength)
69 {
70 return (value == null || value.Length <= maxLength ? value : value.Substring(0, maxLength));
71 }
72
73 /// <summary>
74 /// Trims the text to a provided maximum length and adds a suffix if required.
75 /// </summary>
76 /// <param name="value">The input string.</param>
77 /// <param name="maxLength">Maximum length.</param>
78 /// <param name="suffix">The suffix.</param>
79 /// <returns></returns>
80 /// <remarks>Proposed by Rene Schulte</remarks>
81 public static string TrimToMaxLength(this string value, int maxLength, string suffix)
82 {
83 return (value == null || value.Length <= maxLength ? value : string.Concat(value.Substring(0, maxLength), suffix));
84 }
85
86 /// <summary>
87 /// Determines whether the comparison value strig is contained within the input value string
88 /// </summary>
89 /// <param name="inputValue">The input value.</param>
90 /// <param name="comparisonValue">The comparison value.</param>
91 /// <param name="comparisonType">Type of the comparison to allow case sensitive or insensitive comparison.</param>
92 /// <returns>
93 /// <c>true</c> if input value contains the specified value, otherwise, <c>false</c>.
94 /// </returns>
95 public static bool Contains(this string inputValue, string comparisonValue, StringComparison comparisonType)
96 {
97 return (inputValue.IndexOf(comparisonValue, comparisonType) != -1);
98 }
99
100 /// <summary>
101 /// Loads the string into a LINQ to XML XDocument
102 /// </summary>
103 /// <param name="xml">The XML string.</param>
104 /// <returns>The XML document object model (XDocument)</returns>
105 public static XDocument ToXDocument(this string xml)
106 {
107 return XDocument.Parse(xml);
108 }
109
110 /// <summary>
111 /// Loads the string into a XML DOM object (XmlDocument)
112 /// </summary>
113 /// <param name="xml">The XML string.</param>
114 /// <returns>The XML document object model (XmlDocument)</returns>
115 public static XmlDocument ToXmlDOM(this string xml)
116 {
117 var document = new XmlDocument();
118
119 document.LoadXml(xml);
120
121 return document;
122 }
123
124 /// <summary>
125 /// Loads the string into a XML XPath DOM (XPathDocument)
126 /// </summary>
127 /// <param name="xml">The XML string.</param>
128 /// <returns>The XML XPath document object model (XPathNavigator)</returns>
129 public static XPathNavigator ToXPath(this string xml)
130 {
131 var document = new XPathDocument(new StringReader(xml));
132
133 return document.CreateNavigator();
134 }
135
136 /// <summary>
137 /// Reverses / mirrors a string.
138 /// </summary>
139 /// <param name="value">The string to be reversed.</param>
140 /// <returns>The reversed string</returns>
141 public static string Reverse(this string value)
142 {
143 if (value.IsEmpty() || (value.Length == 1))
144 {
145 return value;
146 }
147
148 var chars = value.ToCharArray();
149
150 Array.Reverse(chars);
151
152 return new string(chars);
153 }
154
155 /// <summary>
156 /// Ensures that a string starts with a given prefix.
157 /// </summary>
158 /// <param name="value">The string value to check.</param>
159 /// <param name="prefix">The prefix value to check for.</param>
160 /// <returns>The string value including the prefix</returns>
161 /// <example>
162 /// <code>
163 /// var extension = "txt";
164 /// var fileName = string.Concat(file.Name, extension.EnsureStartsWith("."));
165 /// </code>
166 /// </example>
167 public static string EnsureStartsWith(this string value, string prefix)
168 {
169 if (value.StartsWith(prefix))
170 {
171 return value;
172 }
173
174 return string.Concat(prefix, value);
175 }
176
177 /// <summary>
178 /// Ensures that a string ends with a given suffix.
179 /// </summary>
180 /// <param name="value">The string value to check.</param>
181 /// <param name="suffix">The suffix value to check for.</param>
182 /// <returns>The string value including the suffix</returns>
183 /// <example>
184 /// <code>
185 /// var url = "http://www.pgk.de";
186 /// url = url.EnsureEndsWith("/"));
187 /// </code>
188 /// </example>
189 public static string EnsureEndsWith(this string value, string suffix)
190 {
191 if (value.EndsWith(suffix))
192 {
193 return value;
194 }
195
196 return string.Concat(value, suffix);
197 }
198
199 #endregion
200
201 #region · Regex based extension methods ·
202
203 /// <summary>
204 /// Uses regular expressions to determine if the string matches to a given regex pattern.
205 /// </summary>
206 /// <param name="value">The input string.</param>
207 /// <param name="regexPattern">The regular expression pattern.</param>
208 /// <returns>
209 /// <c>true</c> if the value is matching to the specified pattern; otherwise, <c>false</c>.
210 /// </returns>
211 /// <example>
212 /// <code>
213 /// var s = "12345";
214 /// var isMatching = s.IsMatchingTo(@"^\d+$");
215 /// </code>
216 /// </example>
217 public static bool IsMatchingTo(this string value, string regexPattern)
218 {
219 return IsMatchingTo(value, regexPattern, RegexOptions.None);
220 }
221
222 /// <summary>
223 /// Uses regular expressions to determine if the string matches to a given regex pattern.
224 /// </summary>
225 /// <param name="value">The input string.</param>
226 /// <param name="regexPattern">The regular expression pattern.</param>
227 /// <param name="options">The regular expression options.</param>
228 /// <returns>
229 /// <c>true</c> if the value is matching to the specified pattern; otherwise, <c>false</c>.
230 /// </returns>
231 /// <example>
232 /// <code>
233 /// var s = "12345";
234 /// var isMatching = s.IsMatchingTo(@"^\d+$");
235 /// </code>
236 /// </example>
237 public static bool IsMatchingTo(this string value, string regexPattern, RegexOptions options)
238 {
239 return Regex.IsMatch(value, regexPattern, options);
240 }
241
242 /// <summary>
243 /// Uses regular expressions to replace parts of a string.
244 /// </summary>
245 /// <param name="value">The input string.</param>
246 /// <param name="regexPattern">The regular expression pattern.</param>
247 /// <param name="replaceValue">The replacement value.</param>
248 /// <returns>The newly created string</returns>
249 /// <example>
250 /// <code>
251 /// var s = "12345";
252 /// var replaced = s.ReplaceWith(@"\d", m => string.Concat(" -", m.Value, "- "));
253 /// </code>
254 /// </example>
255 public static string ReplaceWith(this string value, string regexPattern, string replaceValue)
256 {
257 return ReplaceWith(value, regexPattern, replaceValue, RegexOptions.None);
258 }
259
260 /// <summary>
261 /// Uses regular expressions to replace parts of a string.
262 /// </summary>
263 /// <param name="value">The input string.</param>
264 /// <param name="regexPattern">The regular expression pattern.</param>
265 /// <param name="replaceValue">The replacement value.</param>
266 /// <param name="options">The regular expression options.</param>
267 /// <returns>The newly created string</returns>
268 /// <example>
269 /// <code>
270 /// var s = "12345";
271 /// var replaced = s.ReplaceWith(@"\d", m => string.Concat(" -", m.Value, "- "));
272 /// </code>
273 /// </example>
274 public static string ReplaceWith(this string value, string regexPattern, string replaceValue, RegexOptions options)
275 {
276 return Regex.Replace(value, regexPattern, replaceValue, options);
277 }
278
279 /// <summary>
280 /// Uses regular expressions to replace parts of a string.
281 /// </summary>
282 /// <param name="value">The input string.</param>
283 /// <param name="regexPattern">The regular expression pattern.</param>
284 /// <param name="evaluator">The replacement method / lambda expression.</param>
285 /// <returns>The newly created string</returns>
286 /// <example>
287 /// <code>
288 /// var s = "12345";
289 /// var replaced = s.ReplaceWith(@"\d", m => string.Concat(" -", m.Value, "- "));
290 /// </code>
291 /// </example>
292 public static string ReplaceWith(this string value, string regexPattern, MatchEvaluator evaluator)
293 {
294 return ReplaceWith(value, regexPattern, RegexOptions.None, evaluator);
295 }
296
297 /// <summary>
298 /// Uses regular expressions to replace parts of a string.
299 /// </summary>
300 /// <param name="value">The input string.</param>
301 /// <param name="regexPattern">The regular expression pattern.</param>
302 /// <param name="options">The regular expression options.</param>
303 /// <param name="evaluator">The replacement method / lambda expression.</param>
304 /// <returns>The newly created string</returns>
305 /// <example>
306 /// <code>
307 /// var s = "12345";
308 /// var replaced = s.ReplaceWith(@"\d", m => string.Concat(" -", m.Value, "- "));
309 /// </code>
310 /// </example>
311 public static string ReplaceWith(this string value, string regexPattern, RegexOptions options, MatchEvaluator evaluator)
312 {
313 return Regex.Replace(value, regexPattern, evaluator, options);
314 }
315
316 /// <summary>
317 /// Uses regular expressions to determine all matches of a given regex pattern.
318 /// </summary>
319 /// <param name="value">The input string.</param>
320 /// <param name="regexPattern">The regular expression pattern.</param>
321 /// <returns>A collection of all matches</returns>
322 public static MatchCollection GetMatches(this string value, string regexPattern)
323 {
324 return GetMatches(value, regexPattern, RegexOptions.None);
325 }
326
327 /// <summary>
328 /// Uses regular expressions to determine all matches of a given regex pattern.
329 /// </summary>
330 /// <param name="value">The input string.</param>
331 /// <param name="regexPattern">The regular expression pattern.</param>
332 /// <param name="options">The regular expression options.</param>
333 /// <returns>A collection of all matches</returns>
334 public static MatchCollection GetMatches(this string value, string regexPattern, RegexOptions options)
335 {
336 return Regex.Matches(value, regexPattern, options);
337 }
338
339 /// <summary>
340 /// Uses regular expressions to determine all matches of a given regex pattern and returns them as string enumeration.
341 /// </summary>
342 /// <param name="value">The input string.</param>
343 /// <param name="regexPattern">The regular expression pattern.</param>
344 /// <returns>An enumeration of matching strings</returns>
345 /// <example>
346 /// <code>
347 /// var s = "12345";
348 /// foreach(var number in s.GetMatchingValues(@"\d")) {
349 /// Console.WriteLine(number);
350 /// }
351 /// </code>
352 /// </example>
353 public static IEnumerable<string> GetMatchingValues(this string value, string regexPattern)
354 {
355 return GetMatchingValues(value, regexPattern, RegexOptions.None);
356 }
357
358 /// <summary>
359 /// Uses regular expressions to determine all matches of a given regex pattern and returns them as string enumeration.
360 /// </summary>
361 /// <param name="value">The input string.</param>
362 /// <param name="regexPattern">The regular expression pattern.</param>
363 /// <param name="options">The regular expression options.</param>
364 /// <returns>An enumeration of matching strings</returns>
365 /// <example>
366 /// <code>
367 /// var s = "12345";
368 /// foreach(var number in s.GetMatchingValues(@"\d")) {
369 /// Console.WriteLine(number);
370 /// }
371 /// </code>
372 /// </example>
373 public static IEnumerable<string> GetMatchingValues(this string value, string regexPattern, RegexOptions options)
374 {
375 foreach (Match match in GetMatches(value, regexPattern, options))
376 {
377 if (match.Success)
378 {
379 yield return match.Value;
380 }
381 }
382 }
383
384 /// <summary>
385 /// Uses regular expressions to split a string into parts.
386 /// </summary>
387 /// <param name="value">The input string.</param>
388 /// <param name="regexPattern">The regular expression pattern.</param>
389 /// <returns>The splitted string array</returns>
390 public static string[] Split(this string value, string regexPattern)
391 {
392 return value.Split(regexPattern, RegexOptions.None);
393 }
394
395 /// <summary>
396 /// Uses regular expressions to split a string into parts.
397 /// </summary>
398 /// <param name="value">The input string.</param>
399 /// <param name="regexPattern">The regular expression pattern.</param>
400 /// <param name="options">The regular expression options.</param>
401 /// <returns>The splitted string array</returns>
402 public static string[] Split(this string value, string regexPattern, RegexOptions options)
403 {
404 return Regex.Split(value, regexPattern, options);
405 }
406
407 /// <summary>
408 /// Splits the given string into words and returns a string array.
409 /// </summary>
410 /// <param name="value">The input string.</param>
411 /// <returns>The splitted string array</returns>
412 public static string[] GetWords(this string value)
413 {
414 return value.Split(@"\W");
415 }
416
417 /// <summary>
418 /// Gets the nth "word" of a given string, where "words" are substrings separated by a given separator
419 /// </summary>
420 /// <param name="value">The string from which the word should be retrieved.</param>
421 /// <param name="index">Index of the word (0-based).</param>
422 /// <returns>
423 /// The word at position n of the string.
424 /// Trying to retrieve a word at a position lower than 0 or at a position where no word exists results in an exception.
425 /// </returns>
426 /// <remarks>Originally contributed by MMathews</remarks>
427 public static string GetWordByIndex(this string value, int index)
428 {
429 var words = value.GetWords();
430
431 if ((index < 0) || (index > words.Length - 1))
432 {
433 throw new IndexOutOfRangeException("The word number is out of range.");
434 }
435
436 return words[index];
437 }
438
439 #endregion
440
441 #region · Bytes & Base64 ·
442
443 /// <summary>
444 /// Converts the string to a byte-array using the default encoding
445 /// </summary>
446 /// <param name="value">The input string.</param>
447 /// <returns>The created byte array</returns>
448 public static byte[] ToBytes(this string value)
449 {
450 return value.ToBytes(null);
451 }
452
453 /// <summary>
454 /// Converts the string to a byte-array using the supplied encoding
455 /// </summary>
456 /// <param name="value">The input string.</param>
457 /// <param name="encoding">The encoding to be used.</param>
458 /// <returns>The created byte array</returns>
459 /// <example><code>
460 /// var value = "Hello World";
461 /// var ansiBytes = value.ToBytes(Encoding.GetEncoding(1252)); // 1252 = ANSI
462 /// var utf8Bytes = value.ToBytes(Encoding.UTF8);
463 /// </code></example>
464 public static byte[] ToBytes(this string value, Encoding encoding)
465 {
466 encoding = (encoding ?? Encoding.Default);
467 return encoding.GetBytes(value);
468 }
469
470 /// <summary>
471 /// Encodes the input value to a Base64 string using the default encoding.
472 /// </summary>
473 /// <param name="value">The input value.</param>
474 /// <returns>The Base 64 encoded string</returns>
475 public static string EncodeBase64(this string value)
476 {
477 return value.EncodeBase64(null);
478 }
479
480 /// <summary>
481 /// Encodes the input value to a Base64 string using the supplied encoding.
482 /// </summary>
483 /// <param name="value">The input value.</param>
484 /// <param name="encoding">The encoding.</param>
485 /// <returns>The Base 64 encoded string</returns>
486 public static string EncodeBase64(this string value, Encoding encoding)
487 {
488 encoding = (encoding ?? Encoding.UTF8);
489
490 var bytes = encoding.GetBytes(value);
491
492 return Convert.ToBase64String(bytes);
493 }
494
495 /// <summary>
496 /// Decodes a Base 64 encoded value to a string using the default encoding.
497 /// </summary>
498 /// <param name="encodedValue">The Base 64 encoded value.</param>
499 /// <returns>The decoded string</returns>
500 public static string DecodeBase64(this string encodedValue)
501 {
502 return encodedValue.DecodeBase64(null);
503 }
504
505 /// <summary>
506 /// Decodes a Base 64 encoded value to a string using the supplied encoding.
507 /// </summary>
508 /// <param name="encodedValue">The Base 64 encoded value.</param>
509 /// <param name="encoding">The encoding.</param>
510 /// <returns>The decoded string</returns>
511 public static string DecodeBase64(this string encodedValue, Encoding encoding)
512 {
513 encoding = (encoding ?? Encoding.UTF8);
514
515 var bytes = Convert.FromBase64String(encodedValue);
516
517 return encoding.GetString(bytes);
518 }
519
520 #endregion
521
522 #endregion
523 }
524 }