C# string 常用功能的方法扩展

  1 #region Usings
  2 using System;
  3 using System.Text;
  4 using System.Data;
  5 using System.Data.SqlClient;
  6 using System.Text.RegularExpressions;
  7 using System.Linq;
  8 using System.Collections.Generic;
  9 using System.ComponentModel;
 10 using DragonUtility.DataTypes.Formatters;
 11 using Microsoft.VisualBasic;
 12 #endregion
 13 
 14 namespace DragonUtility.DataTypes.ExtensionMethods
 15 {
 16     /// <summary>
 17     /// String extensions
 18     /// </summary>
 19     public static class StringExtensions
 20     {
 21         #region Functions
 22 
 23         #region Encode
 24 
 25         /// <summary>
 26         /// 编码转换,把字符串从一种编码转换到另一种编码
 27         /// </summary>
 28         /// <param name="Input">input string</param>
 29         /// <param name="OriginalEncodingUsing">The type of encoding the string is currently using (defaults to ASCII)</param>
 30         /// <param name="EncodingUsing">The type of encoding the string is converted into (defaults to UTF8)</param>
 31         /// <returns>string of the byte array</returns>
 32         public static string Encode(this string Input, Encoding OriginalEncodingUsing = null, Encoding EncodingUsing = null)
 33         {
 34             if (string.IsNullOrEmpty(Input))
 35                 return "";
 36             OriginalEncodingUsing = OriginalEncodingUsing.NullCheck(new ASCIIEncoding());
 37             EncodingUsing = EncodingUsing.NullCheck(new UTF8Encoding());
 38             return Encoding.Convert(OriginalEncodingUsing, EncodingUsing, Input.ToByteArray(OriginalEncodingUsing))
 39                            .ToEncodedString(EncodingUsing);
 40           
 41         }
 42         #endregion
 43 
 44         #region FromBase64
 45 
 46         /// <summary>
 47         /// Converts base 64 string based on the encoding passed in
 48         /// </summary>
 49         /// <param name="Input">Input string</param>
 50         /// <param name="EncodingUsing">The type of encoding the string is using (defaults to UTF8)</param>
 51         /// <returns>string in the encoding format</returns>
 52         public static string FromBase64(this string Input, Encoding EncodingUsing)
 53         {
 54             if (string.IsNullOrEmpty(Input))
 55                 return "";
 56             byte[] TempArray = Convert.FromBase64String(Input);
 57             return EncodingUsing.NullCheck(new UTF8Encoding()).GetString(TempArray);
 58         }
 59 
 60         /// <summary>
 61         /// Converts base 64 string to a byte array
 62         /// </summary>
 63         /// <param name="Input">Input string</param>
 64         /// <returns>A byte array equivalent of the base 64 string</returns>
 65         public static byte[] FromBase64(this string Input)
 66         {
 67             return string.IsNullOrEmpty(Input) ? new byte[0] : Convert.FromBase64String(Input);
 68         }
 69 
 70         #endregion
 71 
 72         #region Left
 73 
 74         /// <summary>
 75         /// Gets the first x number of characters from the left hand side
 76         /// </summary>
 77         /// <param name="Input">Input string</param>
 78         /// <param name="Length">x number of characters to return</param>
 79         /// <returns>The resulting string</returns>
 80         public static string Left(this string Input, int Length)
 81         {
 82             return string.IsNullOrEmpty(Input) ? "" : Input.Substring(0, Input.Length > Length ? Length : Input.Length);
 83         }
 84 
 85         #endregion
 86 
 87         #region Right
 88 
 89         /// <summary>
 90         /// Gets the last x number of characters from the right hand side
 91         /// </summary>
 92         /// <param name="Input">Input string</param>
 93         /// <param name="Length">x number of characters to return</param>
 94         /// <returns>The resulting string</returns>
 95         public static string Right(this string Input, int Length)
 96         {
 97             if (string.IsNullOrEmpty(Input))
 98                 return "";
 99             Length = Input.Length > Length ? Length : Input.Length;
100             return Input.Substring(Input.Length - Length, Length);
101         }
102 
103         #endregion
104 
105         #region ToBase64
106 
107         /// <summary>
108         /// Converts from the specified encoding to a base 64 string
109         /// </summary>
110         /// <param name="Input">Input string</param>
111         /// <param name="OriginalEncodingUsing">The type of encoding the string is using (defaults to UTF8)</param>
112         /// <returns>Bas64 string</returns>
113         public static string ToBase64(this string Input, Encoding OriginalEncodingUsing = null)
114         {
115             if (string.IsNullOrEmpty(Input))
116                 return "";
117             byte[] TempArray = OriginalEncodingUsing.NullCheck(new UTF8Encoding()).GetBytes(Input);
118             return Convert.ToBase64String(TempArray);
119         }
120 
121         #endregion
122 
123         #region ToByteArray
124 
125         /// <summary>
126         /// Converts a string to a byte array
127         /// </summary>
128         /// <param name="Input">input string</param>
129         /// <param name="EncodingUsing">The type of encoding the string is using (defaults to UTF8)</param>
130         /// <returns>the byte array representing the string</returns>
131         public static byte[] ToByteArray(this string Input, Encoding EncodingUsing = null)
132         {
133             return string.IsNullOrEmpty(Input) ? null : EncodingUsing.NullCheck(new UTF8Encoding()).GetBytes(Input);
134         }
135 
136         #endregion
137 
138         #region ToFirstCharacterUpperCase
139 
140         /// <summary>
141         /// Takes the first character of an input string and makes it uppercase
142         /// </summary>
143         /// <param name="Input">Input string</param>
144         /// <returns>String with the first character capitalized</returns>
145         public static string ToFirstCharacterUpperCase(this string Input)
146         {
147             if (string.IsNullOrEmpty(Input))
148                 return "";
149             char[] InputChars = Input.ToCharArray();
150             for (int x = 0; x < InputChars.Length; ++x)
151             {
152                 if (InputChars[x] != ' ' && InputChars[x] != '\t')
153                 {
154                     InputChars[x] = char.ToUpper(InputChars[x]);
155                     break;
156                 }
157             }
158             return new string(InputChars);
159         }
160 
161         #endregion
162 
163         #region ToSentenceCapitalize
164 
165         /// <summary>
166         /// Capitalizes each sentence within the string
167         /// </summary>
168         /// <param name="Input">Input string</param>
169         /// <returns>String with each sentence capitalized</returns>
170         public static string ToSentenceCapitalize(this string Input)
171         {
172             if (string.IsNullOrEmpty(Input))
173                 return "";
174             string[] Seperator = { ".", "?", "!" };
175             string[] InputStrings = Input.Split(Seperator, StringSplitOptions.None);
176             for (int x = 0; x < InputStrings.Length; ++x)
177             {
178                 if (!string.IsNullOrEmpty(InputStrings[x]))
179                 {
180                     Regex TempRegex = new Regex(InputStrings[x]);
181                     InputStrings[x] = InputStrings[x].ToFirstCharacterUpperCase();
182                     Input = TempRegex.Replace(Input, InputStrings[x]);
183                 }
184             }
185             return Input;
186         }
187 
188         #endregion
189 
190         #region ToTitleCase
191 
192         /// <summary>
193         /// Capitalizes the first character of each word
194         /// </summary>
195         /// <param name="Input">Input string</param>
196         /// <returns>String with each word capitalized</returns>
197         public static string ToTitleCase(this string Input)
198         {
199             if (string.IsNullOrEmpty(Input))
200                 return "";
201             string[] Seperator = { " ", ".", "\t", System.Environment.NewLine, "!", "?" };
202             string[] InputStrings = Input.Split(Seperator, StringSplitOptions.None);
203             for (int x = 0; x < InputStrings.Length; ++x)
204             {
205                 if (!string.IsNullOrEmpty(InputStrings[x])
206                     && InputStrings[x].Length > 3)
207                 {
208                     Regex TempRegex = new Regex(InputStrings[x]);
209                     InputStrings[x] = InputStrings[x].ToFirstCharacterUpperCase();
210                     Input = TempRegex.Replace(Input, InputStrings[x]);
211                 }
212             }
213             return Input;
214         }
215 
216         #endregion
217 
218         #region NumberTimesOccurs
219 
220         /// <summary>
221         /// returns the number of times a string occurs within the text
222         /// </summary>
223         /// <param name="Input">input text</param>
224         /// <param name="Match">The string to match (can be regex)</param>
225         /// <returns>The number of times the string occurs</returns>
226         public static int NumberTimesOccurs(this string Input, string Match)
227         {
228             return string.IsNullOrEmpty(Input) ? 0 : new Regex(Match).Matches(Input).Count;
229         }
230 
231         #endregion
232 
233         #region Reverse
234 
235         /// <summary>
236         /// Reverses a string
237         /// </summary>
238         /// <param name="Input">Input string</param>
239         /// <returns>The reverse of the input string</returns>
240         public static string Reverse(this string Input)
241         {
242             return new string(Input.Reverse<char>().ToArray());
243         }
244 
245         #endregion
246 
247         #region FilterOutText
248 
249         /// <summary>
250         /// Removes the filter text from the input.
251         /// </summary>
252         /// <param name="Input">Input text</param>
253         /// <param name="Filter">Regex expression of text to filter out</param>
254         /// <returns>The input text minus the filter text.</returns>
255         public static string FilterOutText(this string Input, string Filter)
256         {
257             if (string.IsNullOrEmpty(Input))
258                 return "";
259             return string.IsNullOrEmpty(Filter) ? Input : new Regex(Filter).Replace(Input, "");
260         }
261 
262         #endregion
263 
264         #region KeepFilterText
265 
266         /// <summary>
267         /// Removes everything that is not in the filter text from the input.
268         /// </summary>
269         /// <param name="Input">Input text</param>
270         /// <param name="Filter">Regex expression of text to keep</param>
271         /// <returns>The input text minus everything not in the filter text.</returns>
272         public static string KeepFilterText(this string Input, string Filter)
273         {
274             if (string.IsNullOrEmpty(Input) || string.IsNullOrEmpty(Filter))
275                 return "";
276             Regex TempRegex = new Regex(Filter);
277             MatchCollection Collection = TempRegex.Matches(Input);
278             StringBuilder Builder = new StringBuilder();
279             foreach (Match Match in Collection)
280                 Builder.Append(Match.Value);
281             return Builder.ToString();
282         }
283 
284         #endregion
285 
286         #region AlphaNumericOnly
287 
288         /// <summary>
289         /// Keeps only alphanumeric characters
290         /// </summary>
291         /// <param name="Input">Input string</param>
292         /// <returns>the string only containing alphanumeric characters</returns>
293         public static string AlphaNumericOnly(this string Input)
294         {
295             return Input.KeepFilterText("[a-zA-Z0-9]");
296         }
297 
298         #endregion
299 
300         #region AlphaCharactersOnly
301 
302         /// <summary>
303         /// Keeps only alpha characters
304         /// </summary>
305         /// <param name="Input">Input string</param>
306         /// <returns>the string only containing alpha characters</returns>
307         public static string AlphaCharactersOnly(this string Input)
308         {
309             return Input.KeepFilterText("[a-zA-Z]");
310         }
311 
312         #endregion
313 
314         #region NumericOnly
315 
316         /// <summary>
317         /// Keeps only numeric characters
318         /// </summary>
319         /// <param name="Input">Input string</param>
320         /// <param name="KeepNumericPunctuation">Determines if decimal places should be kept</param>
321         /// <returns>the string only containing numeric characters</returns>
322         public static string NumericOnly(this string Input, bool KeepNumericPunctuation = true)
323         {
324             return KeepNumericPunctuation ? Input.KeepFilterText(@"[0-9\.]") : Input.KeepFilterText("[0-9]");
325         }
326 
327         #endregion
328 
329         #region IsUnicode
330 
331         /// <summary>
332         /// Determines if a string is unicode
333         /// </summary>
334         /// <param name="Input">Input string</param>
335         /// <returns>True if it's unicode, false otherwise</returns>
336         public static bool IsUnicode(this string Input)
337         {
338             return string.IsNullOrEmpty(Input) ? true : Regex.Replace(Input, @"[^\u0000-\u007F]", "") != Input;
339         }
340 
341         #endregion
342 
343         #region FormatString
344 
345         /// <summary>
346         /// Formats a string based on a format string passed in:
347         /// # = digits
348         /// @ = alpha characters
349         /// \ = escape char
350         /// </summary>
351         /// <param name="Input">Input string</param>
352         /// <param name="Format">Format of the output string</param>
353         /// <returns>The formatted string</returns>
354         public static string FormatString(this string Input, string Format)
355         {
356             return new GenericStringFormatter().Format(Input, Format);
357         }
358 
359         #endregion
360 
361         #region RegexFormat
362 
363         /// <summary>
364         /// Uses a regex to format the input string
365         /// </summary>
366         /// <param name="Input">Input string</param>
367         /// <param name="Format">Regex string used to</param>
368         /// <param name="OutputFormat">Output format</param>
369         /// <param name="Options">Regex options</param>
370         /// <returns>The input string formatted by using the regex string</returns>
371         public static string RegexFormat(this string Input, string Format, string OutputFormat, RegexOptions Options = RegexOptions.None)
372         {
373             Input.ThrowIfNullOrEmpty("Input");
374             return Regex.Replace(Input, Format, OutputFormat, Options);
375         }
376 
377         #endregion
378 
379         #region 转换
380         /// <summary>
381         /// 全角转半角
382         /// </summary>
383         /// <param name="input">要转换的字符串</param>
384         /// <returns>转换完的字符串</returns>
385         public static string Narrow(this string input)
386         {
387             return Strings.StrConv(input, VbStrConv.Narrow, 0);
388         }
389         /// <summary>
390         /// 半角转全角
391         /// </summary>
392         /// <param name="input">要转换的字符串</param>
393         /// <returns>转换完的字符串</returns>
394         public static string Wide(this string input)
395         {
396             return Strings.StrConv(input, VbStrConv.Wide, 0);
397         }
398         /// <summary>
399         /// 简体转繁体
400         /// </summary>
401         /// <param name="input"></param>
402         /// <returns></returns>
403         public static string TraditionalChinese(this string input)
404         {
405             return Strings.StrConv(input, VbStrConv.TraditionalChinese, 0);
406         }
407         /// <summary>
408         /// 繁体转简体
409         /// </summary>
410         /// <param name="input"></param>
411         /// <returns></returns>
412         public static string SimplifiedChinese(this string input)
413         {
414             return Strings.StrConv(input, VbStrConv.SimplifiedChinese, 0);
415         }
416         /// <summary>
417         /// 将每个单词首字母大写
418         /// </summary>
419         /// <param name="input"></param>
420         /// <returns></returns>
421         public static string ProperCase(this string input)
422         {
423             return Strings.StrConv(input, VbStrConv.ProperCase, 0);
424         }
425         #endregion
426 
427         #endregion
428     }
429 }

 

posted @ 2018-10-11 14:22 Mr.石 阅读(...) 评论(...) 编辑 收藏

公告