2 using System.Collections.Generic;
6 using System.Text.RegularExpressions;
10 using System.Xml.Serialization;
18 public static class StringExtensions
26 public static string RemoveLastChars(
this string Input,
int NumberOfCharsToRemove)
28 if (NumberOfCharsToRemove <= 0)
return Input;
29 return (Input.Length > NumberOfCharsToRemove ? Input.Substring(0, Input.Length - NumberOfCharsToRemove) :
"");
40 public static string RemoveSpecifiedEnd(
this string Input,
string StringEndToRemove, StringComparison ComparisonType = StringComparison.CurrentCulture)
42 return Input.EndsWith(StringEndToRemove, ComparisonType) ? Input.RemoveLastChars(StringEndToRemove.Length) : Input;
52 public static string RemoveRemoveConsecutiveWhiteSpaces(
this string Input)
54 return Regex.Replace(Input,
@"\s+",
" ");
62 public static string RemoveWhitespaces(
this string input)
64 return new string(input.ToCharArray()
65 .Where(c => !Char.IsWhiteSpace(c))
73 public static int HexToInt(
this string s)
75 return int.Parse(s,
System.Globalization.NumberStyles.HexNumber);
81 public static int HexToByte(
this string s)
83 return byte.Parse(s,
System.Globalization.NumberStyles.HexNumber);
89 public static bool IsHexString(
this string s)
91 return s.IsHexString(0, s.Length);
101 public static bool IsHexString(
this string s,
int startindex)
103 return s.IsHexString(startindex, s.Length - startindex);
114 public static bool IsHexString(
this string s,
int startindex,
int length)
116 if (
string.IsNullOrWhiteSpace(s))
return false;
118 if (startindex + length > s.Length)
return false;
120 return System.Text.RegularExpressions.Regex.IsMatch(s.Substring(startindex, length),
@"\A\b[0-9a-fA-F]+\b\Z");
130 public static byte[] ToByteArray(
this string s)
132 System.Text.UTF8Encoding encoding =
new System.Text.UTF8Encoding();
133 return encoding.GetBytes(s);
140 public static StringBuilder ToStringBuilder(
this string s)
142 if (
string.IsNullOrEmpty(s))
144 return new StringBuilder(
"");
146 return new StringBuilder(s);
154 public static string Left(
this string s,
int length)
156 return s.Substring(0, length);
164 public static string Right(
this string s,
int length)
166 return s.Substring(s.Length - length, length);
176 public static string Mid(
this string s,
int startIndex,
int length)
178 return s.Substring(startIndex, length);
185 public static int ToInteger(
this string s)
187 int integerValue = 0;
188 int.TryParse(s, out integerValue);
196 public static uint ToUInt(
this string s)
198 uint uintegerValue = 0;
199 uint.TryParse(s, out uintegerValue);
200 return uintegerValue;
207 public static bool IsInteger(
this string s)
210 if (s.IsNullOrWhiteSpace())
return false;
211 return int.TryParse(s, out dummy);
218 public static bool IsUInt(
this string s)
221 if (s.IsNullOrWhiteSpace())
return false;
222 return uint.TryParse(s, out dummy);
229 public static bool IsNullOrEmpty(
this string s)
231 return string.IsNullOrEmpty(s);
238 public static bool IsNullOrWhiteSpace(
this string s)
240 return string.IsNullOrWhiteSpace(s);
250 public static string Build(
this string s,
object arg0)
252 if (s == null) {
return ""; }
253 return string.Format(s, arg0);
262 public static string Build(
this string s,
object arg0,
object arg1)
264 if (s == null) {
return ""; }
265 return string.Format(s, arg0, arg1);
275 public static string Build(
this string s,
object arg0,
object arg1,
object arg2)
277 if (s == null) {
return ""; }
278 return string.Format(s, arg0, arg1, arg2);
297 public static string Build(
this string s, params
object[] args)
299 if (s == null) {
return ""; }
300 return string.Format(s, args);
311 public static string Construct(
this string s, Dictionary<string, object> ConstructionValueDictionary,
bool ReplaceNullValuesWithEmptyString =
true,
bool IgnoreMissingConstructionValues =
false)
313 if (s.IsNullOrWhiteSpace())
return s;
315 List<string> L = s.GetConstructionItemsList().Select(S => S.Substring(1, S.Length - 2)).ToList();
316 foreach (
string N
in L)
319 if (ConstructionValueDictionary.ContainsKey(N))
321 object O = ConstructionValueDictionary[N];
322 if (O == null && ReplaceNullValuesWithEmptyString)
330 s = s.Replace(
"{{{0}}}".Build(N), V);
332 else if (!IgnoreMissingConstructionValues)
334 throw new ArgumentException(
"The ConstructionValueDictionary does not contain a value for '{0}'".Build(N),
"ConstructionValueDictionary");
345 public static List<string> GetConstructionItemsList(
this string s)
347 List<string> L =
new List<string>();
348 if (!s.IsNullOrWhiteSpace())
350 Regex regex =
new Regex(
"{.*?}");
351 MatchCollection matches = regex.Matches(s);
352 foreach (
object match
in matches)
354 string N = match.ToString();
373 public static Dictionary<string, object> GetConstructionItemsDictionary(
this string s)
375 Dictionary<string, object> D =
new Dictionary<string, object>();
376 List<string> L = s.GetConstructionItemsList();
377 L.ForEach(N => D.Add(N, null));
390 public static bool IsEmail(
this string s)
392 Regex MailCheck =
new Regex(
@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
393 return MailCheck.IsMatch(s);
401 public static void WriteToFile(
this string s,
string FileName)
403 s.WriteToFile(FileName,
false);
411 public static void WriteToFile(
this string s,
string FileName,
bool Append)
413 TextWriter tw = null;
416 tw =
new StreamWriter(FileName, Append);
440 public static void WriteToFile(
this string s, FileInfo File)
442 s.WriteToFile(File.FullName,
false);
451 public static void WriteToFile(
this string s, FileInfo File,
bool Append)
453 s.WriteToFile(File.FullName, Append);
465 static public string Replace(
this string originalString,
string oldValue,
string newValue, StringComparison comparisonType)
467 StringBuilder sb =
new StringBuilder();
469 int previousIndex = 0;
470 int index = originalString.IndexOf(oldValue, comparisonType);
473 sb.Append(originalString.Substring(previousIndex, index - previousIndex));
475 index += oldValue.Length;
477 previousIndex = index;
478 index = originalString.IndexOf(oldValue, index, comparisonType);
480 sb.Append(originalString.Substring(previousIndex));
482 return sb.ToString();
493 public static bool IsAlphaNumeric(
this string str)
495 if (
string.IsNullOrEmpty(str))
498 return !str.Any(C => !
char.IsLetterOrDigit(C));
507 public static string RemoveDiacritics(
this string text)
509 string normalizedString = text.Normalize(NormalizationForm.FormD);
510 StringBuilder stringBuilder =
new StringBuilder();
512 foreach (var c
in normalizedString)
514 UnicodeCategory unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
515 if (unicodeCategory != UnicodeCategory.NonSpacingMark)
517 stringBuilder.Append(c);
521 return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
530 public static string AlternativeWhenNullOrWhiteSpace(
this string text,
string Alternative)
532 if (text.IsNullOrWhiteSpace())
return Alternative;
543 public static T XMLDeserialize<T>(
this string Xml)
545 byte[] xmlBytes = Encoding.Default.GetBytes(Xml);
546 using (MemoryStream ms =
new MemoryStream(xmlBytes))
550 return (T)
new XmlSerializer(typeof(T)).Deserialize(ms);
555 Exception Ex =
new Exception(
"Could not deserialize {0} from XML data.".Build(typeof(T).Name), E);
556 Ex.Data.Add(
"XML Data", Xml);
572 public static object XMLDeserialize(
this string Xml, Type Type)
574 byte[] xmlBytes = Encoding.Default.GetBytes(Xml);
575 using (MemoryStream ms =
new MemoryStream(xmlBytes))
579 return new XmlSerializer(Type).Deserialize(ms);
584 Exception Ex =
new Exception(
"Could not deserialize {0} from XML data.".Build(Type.Name), E);
585 Ex.Data.Add(
"XML Data", Xml);
600 public static T XMLDeserializeInterface<T>(
this string Xml)
602 byte[] xmlBytes = Encoding.Default.GetBytes(Xml);
603 using (MemoryStream ms =
new MemoryStream(xmlBytes))
605 using (XmlReader r = XmlReader.Create(ms))
607 List<Type> Types =
new List<Type>(AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes()).Where(p => typeof(T).IsAssignableFrom(p) && !p.IsAbstract));
609 if (Types.Any(Ty => Ty.FullName == r.LocalName))
611 throw new Exception(
"The type {0} specified in the xml cant be assigned to {1}".Build(r.LocalName, typeof(T).FullName));
613 Type TargetType = Types.First(Ty => Ty.FullName == r.LocalName);
616 return (T)
new XmlSerializer(TargetType).Deserialize(r);
621 Exception Ex =
new Exception(
"Could not deserialize {0} from XML data.".Build(typeof(T).Name), E);
622 Ex.Data.Add(
"XML Data", Xml);
642 public static bool IsValidPath(
this string PathToCheck)
646 Path.GetFullPath(PathToCheck);
662 public static bool IsRelativePath(
this string PathToCheck)
664 if (IsValidPath(PathToCheck))
666 if (!Path.IsPathRooted(PathToCheck))
681 public static DateTime ToDateTime(
this string DateString,
string DateFormat)
683 return DateTime.ParseExact(DateString, DateFormat,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.NoCurrentDateDefault);
693 public static DateTime ToDateTime(
this string DateString,
string[] DateFormats)
695 return DateTime.ParseExact(DateString, DateFormats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.NoCurrentDateDefault);
706 public static bool IsDateTime(
this string DateString,
string[] DateFormats)
708 if (DateString == null)
return false;
710 return (DateTime.TryParseExact(DateString, DateFormats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.NoCurrentDateDefault, out Dummy));
721 public static bool IsDateTime(
this string DateString,
string DateFormat)
723 if (DateString == null)
return false;
725 return (DateTime.TryParseExact(DateString, DateFormat,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.NoCurrentDateDefault, out Dummy));
735 public static string IndentString(
this string StringToIndent,
string IndentionString)
737 if (StringToIndent == null) {
return null; }
738 string[] Parts = StringToIndent.Split(
new string[] {
"\r\n",
"\n" }, StringSplitOptions.None);
739 return IndentionString +
string.Join(Environment.NewLine + IndentionString, Parts);
746 static public byte[] GetBytes(
this string str)
748 byte[] bytes =
new byte[str.Length *
sizeof(char)];
749 System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
Animation steps from left to right through the source image