-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathString.cs
719 lines (646 loc) · 28.6 KB
/
String.cs
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
#region Related components
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Globalization;
#endregion
namespace net.vieapps.Components.Utility
{
/// <summary>
/// Static servicing methods for working with string
/// </summary>
public static partial class StringService
{
#region Manipulations
/// <summary>
/// Gets left-side sub-string (just like VB does)
/// </summary>
/// <param name="string"></param>
/// <param name="length"></param>
/// <returns></returns>
public static string Left(this string @string, int length)
=> length < 0
? throw new ArgumentException($"Argument '{nameof(length)}' must be greater or equal to zero")
: @string.Equals("")
? string.Empty
: length >= @string.Length
? @string
: @string.Substring(0, length);
/// <summary>
/// Gets right-side sub-string (just like VB does)
/// </summary>
/// <param name="string"></param>
/// <param name="length"></param>
/// <returns></returns>
public static string Right(this string @string, int length)
=> length < 0
? throw new ArgumentException($"Argument '{nameof(length)}' must be greater or equal to zero")
: @string.Equals("")
? string.Empty
: length >= @string.Length
? @string
: @string.Substring(@string.Length - length);
/// <summary>
/// Returns a new string that right-aligns the characters in this instance by padding them with spaces on the left, for a specified total length
/// </summary>
/// <param name="string"></param>
/// <param name="totalWidth"></param>
/// <param name="paddingChar"></param>
/// <returns></returns>
public static string PadLeft(this string @string, int totalWidth, string paddingChar = null)
=> string.IsNullOrWhiteSpace(@string)
? ""
: string.IsNullOrWhiteSpace(paddingChar)
? @string.PadLeft(totalWidth)
: @string.PadLeft(totalWidth, paddingChar[0]);
/// <summary>
/// Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length
/// </summary>
/// <param name="string"></param>
/// <param name="totalWidth"></param>
/// <param name="paddingChar"></param>
/// <returns></returns>
public static string PadRight(this string @string, int totalWidth, string paddingChar = null)
=> string.IsNullOrWhiteSpace(@string)
? ""
: string.IsNullOrWhiteSpace(paddingChar)
? @string.PadRight(totalWidth)
: @string.PadRight(totalWidth, paddingChar[0]);
/// <summary>
/// Replaces
/// </summary>
/// <param name="string"></param>
/// <param name="comparisonType"></param>
/// <param name="pattern"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string Replace(this string @string, StringComparison comparisonType, string pattern, string replacement)
{
if (string.IsNullOrWhiteSpace(@string))
return string.Empty;
if (string.IsNullOrWhiteSpace(pattern))
return @string;
#if NETSTANDARD2_0
var result = @string;
var pos = result.IndexOf(pattern, comparisonType);
while (pos > -1)
{
result = result.Remove(pos, pattern.Length);
if (!string.IsNullOrWhiteSpace(replacement))
result = result.Insert(pos, replacement);
pos += string.IsNullOrWhiteSpace(replacement)
? 1
: replacement.Length;
pos = pos < result.Length
? result.IndexOf(pattern, pos, comparisonType)
: -1;
}
return result;
#else
return @string.Replace(pattern, replacement, comparisonType);
#endif
}
#endregion
#region Comparisons
/// <summary>
/// Checks to see the string is numeric string or not
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static bool IsNumeric(this string @string)
=> !string.IsNullOrWhiteSpace(@string) && double.TryParse(@string, out var number);
/// <summary>
/// Check to see its equals
/// </summary>
/// <param name="string"></param>
/// <param name="compareTo"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
public static bool IsEquals(this string @string, string compareTo, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> string.IsNullOrWhiteSpace(compareTo)
? string.IsNullOrWhiteSpace(@string)
: @string.Equals(compareTo, comparisonType);
/// <summary>
/// Check to see its contains
/// </summary>
/// <param name="string"></param>
/// <param name="substring"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
public static bool IsContains(this string @string, string substring, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> !string.IsNullOrWhiteSpace(@string) && !string.IsNullOrWhiteSpace(substring) && @string.IndexOf(substring, 0, comparisonType) > -1;
/// <summary>
/// Check to see its starts with
/// </summary>
/// <param name="string"></param>
/// <param name="substring"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
public static bool IsStartsWith(this string @string, string substring, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> !string.IsNullOrWhiteSpace(@string) && !string.IsNullOrWhiteSpace(substring) && @string.StartsWith(substring, comparisonType);
/// <summary>
/// Check to see its starts with
/// </summary>
/// <param name="string"></param>
/// <param name="char"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
public static bool IsStartsWith(this string @string, char @char, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> !string.IsNullOrWhiteSpace(@string) && @string.IsStartsWith($"{@char}", comparisonType);
/// <summary>
/// Check to see its ends with
/// </summary>
/// <param name="string"></param>
/// <param name="substring"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
public static bool IsEndsWith(this string @string, string substring, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> !string.IsNullOrWhiteSpace(@string) && !string.IsNullOrWhiteSpace(substring) && @string.EndsWith(substring, comparisonType);
/// <summary>
/// Check to see its ends with
/// </summary>
/// <param name="string"></param>
/// <param name="char"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
public static bool IsEndsWith(this string @string, char @char, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> !string.IsNullOrWhiteSpace(@string) && @string.IsEndsWith($"{@char}", comparisonType);
/// <summary>
/// Gets position of sub-string (index of sub-string)
/// </summary>
/// <param name="string"></param>
/// <param name="substring"></param>
/// <param name="startIndex"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
public static int PositionOf(this string @string, string substring, int startIndex = 0, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
=> string.IsNullOrWhiteSpace(@string) || string.IsNullOrWhiteSpace(substring) || startIndex >= @string.Length
? -1
: @string.IndexOf(substring, startIndex < 0 ? 0 : startIndex, comparisonType);
/// <summary>
/// Counts the number of appearances of the sub-string
/// </summary>
/// <param name="string"></param>
/// <param name="substring"></param>
/// <param name="startIndex"></param>
/// <param name="comparisonType"></param>
/// <returns></returns>
public static int Count(this string @string, string substring, int startIndex = 0, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
if (string.IsNullOrWhiteSpace(@string) || string.IsNullOrWhiteSpace(substring))
return 0;
var count = 0;
var start = @string.PositionOf(substring, startIndex < 0 ? 0 : startIndex, comparisonType);
while (start > -1)
{
count++;
start = @string.PositionOf(substring, start + 1, comparisonType);
}
return count;
}
#endregion
#region Compressions
/// <summary>
/// Compresses the string using Deflate compression method
/// </summary>
/// <param name="string"></param>
/// <param name="mode">Compression mode (br/gzip/deflate)</param>
/// <returns>The compressed-string in Base64 format</returns>
public static string Compress(this string @string, string mode = "deflate")
=> string.IsNullOrWhiteSpace(@string)
? ""
: @string.ToBytes().Compress(mode).ToBase64();
/// <summary>
/// Decompresses the Base64 string using Deflate compression method
/// </summary>
/// <param name="string"></param>
/// <param name="mode">Decompression mode (br/gzip/deflate)</param>
/// <returns>The decompressed-string</returns>
public static string Decompress(this string @string, string mode = "deflate")
=> string.IsNullOrWhiteSpace(@string)
? ""
: @string.Base64ToBytes().Decompress(mode).GetString();
#endregion
#region Conversions
/// <summary>
/// Gets reversed string
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string Reverse(this string @string)
{
if (@string.Equals("") || @string.Length < 2)
return @string;
var chars = @string.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
/// <summary>
/// Gets the string with first-letter is capitalized
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string GetCapitalizedFirstLetter(this string @string, bool wordsSeperatedByDots = true)
{
if (string.IsNullOrWhiteSpace(@string))
return "";
if (wordsSeperatedByDots)
return @string.ToArray(".").Select(str =>
{
var chars = str.ToLower().ToCharArray();
chars[0] = char.ToUpper(chars[0]);
return new string(chars);
}).Join(".");
else
{
var chars = @string.ToLower().ToCharArray();
chars[0] = char.ToUpper(chars[0]);
return new string(chars);
}
}
/// <summary>
/// Gets the string with first-letter of all words is capitalized
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string GetCapitalizedWords(this string @string)
=> CultureInfo.CurrentCulture.TextInfo.ToTitleCase(@string);
/// <summary>
/// Converts this integer to enum type value
/// </summary>
/// <param name="int"></param>
/// <param name="type">The type of enum</param>
/// <returns></returns>
public static object ToEnum(this int @int, Type type)
=> type != null && type.IsEnum
? Enum.ToObject(type, @int)
: throw new ArgumentException($"The type '{nameof(type)}' is not enum");
/// <summary>
/// Converts this integer to enum type value
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="int"></param>
/// <returns></returns>
public static T ToEnum<T>(this int @int)
=> (T)@int.ToEnum(typeof(T));
/// <summary>
/// Converts this enum-string to enum type value
/// </summary>
/// <param name="string"></param>
/// <param name="type">The type of enum</param>
/// <returns></returns>
public static object ToEnum(this string @string, Type type)
=> type != null && type.IsEnum
? Enum.Parse(type, @string)
: throw new ArgumentException($"The type '{nameof(type)}' is not enum");
/// <summary>
/// Converts this enum-string to enum type value
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="string"></param>
/// <returns></returns>
public static T ToEnum<T>(this string @string)
=> (T)@string.ToEnum(typeof(T));
/// <summary>
/// Trys to converts this enum-string to enum-typed value
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="string"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool TryToEnum<T>(this string @string, out T value) where T : struct
=> typeof(T).IsEnum
? Enum.TryParse(@string, out value)
: throw new ArgumentException($"The type '{typeof(T).GetType()}' is not enum");
/// <summary>
/// Gets the string from array of bytes by specified encoding (default is UTF8)
/// </summary>
/// <param name="bytes"></param>
/// <param name="count"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string GetString(this byte[] bytes, int count = 0, Encoding encoding = null)
=> (encoding ?? Encoding.UTF8).GetString(bytes, 0, count > 0 ? count : bytes.Length);
/// <summary>
/// Gets the string from array of bytes by specified encoding (default is UTF8)
/// </summary>
/// <param name="bytes"></param>
/// <param name="count"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string GetString(this ArraySegment<byte> bytes, int count = 0, Encoding encoding = null)
=> bytes.ToBytes(count).GetString(0, encoding);
/// <summary>
/// Gets the double braces (mustache-style - {{ }}) tokens
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static List<Tuple<string, string>> GetDoubleBracesTokens(this string @string)
{
var tokens = new List<Tuple<string, string>>();
if (!string.IsNullOrWhiteSpace(@string))
{
var matches = new Regex("{{([^{}]*)}}", RegexOptions.IgnoreCase).Matches(@string);
foreach (Match match in matches)
tokens.Add(new Tuple<string, string>(match.Groups[0].Value, match.Groups[1].Value.Trim()));
}
return tokens;
}
/// <summary>
/// Formats the string with parameters of double braces (mustache-style - {{ }}) tokens
/// </summary>
/// <param name="string"></param>
/// <param name="params"></param>
/// <returns></returns>
public static string Format(this string @string, IDictionary<string, object> @params)
{
var tokens = @string?.GetDoubleBracesTokens();
@params?.ForEach(kvp => tokens?.Where(token => token.Item2.IsEquals(kvp.Key)).ForEach(token => @string = @string?.Replace(StringComparison.OrdinalIgnoreCase, token.Item1, $"{kvp.Value}")));
return @string;
}
#endregion
#region Validations (Email/Phone)
/// <summary>
/// Validates an email address
/// </summary>
/// <param name="input"></param>
/// <param name="output"></param>
/// <returns></returns>
public static bool IsValidEmail(this string input, out string output)
{
output = (input ?? "").Replace(" ", "").Replace("#", "").Trim().ToLower();
var regex = new Regex("^(([^<>()[\\]\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(([^<>()[\\]\\.,;:\\s@\\\"]+\\.)+[^<>()[\\]\\.,;:\\s@\\\"]{2,})$", RegexOptions.IgnoreCase);
if (string.IsNullOrWhiteSpace(output) || !regex.IsMatch(output))
{
output = null;
return false;
}
return true;
}
/// <summary>
/// Validates a phone number
/// </summary>
/// <param name="input"></param>
/// <param name="output"></param>
/// <param name="phoneCountryCode"></param>
/// <returns></returns>
public static bool IsValidPhone(this string input, out string output, string phoneCountryCode = "84")
{
output = (input ?? "").Replace(" ", "").Replace("-", "").Replace(".", "").Trim();
var regex = new Regex("^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$", RegexOptions.IgnoreCase);
if (string.IsNullOrWhiteSpace(output) || !regex.IsMatch(output))
{
output = null;
return false;
}
if (output.StartsWith("00"))
output = $"+{output.Right(output.Length - 2)}";
if (output.StartsWith("0"))
output = $"+{phoneCountryCode ?? "84"}{output.Right(output.Length - 1)}";
return true;
}
#endregion
#region Conversions (Vietnamese)
internal static string ConvertVietnamese(this string @string, int mode)
{
if (string.IsNullOrWhiteSpace(@string))
return string.Empty;
var utf8Literal = "à á ả ã ạ À à Ả Ã Ạâ ầ ấ ẩ ẫ ẠÂ Ầ Ấ Ẩ Ẫ Ậ ă ằ ắ ẳ ẵ ặ Ă Ằ Ắ Ẳ Ẵ Ặ "
+ "ò ó Ỡõ á» Ã’ Ó Ỏ Õ Ọ ô ồ ố ổ á»— á»™ Ô á»’ á» á»” á»– Ộ Æ¡ á» á»› ở ỡ ợ Æ á»œ Ớ Ở ỠỢ "
+ "è é ẻ ẽ ẹ È É Ẻ Ẽ Ẹ ê Ỡế ể ễ ệ Ê Ề Ế Ể Ễ Ệ "
+ "ù ú ủ ũ ụ Ù Ú Ủ Ũ Ụ ư ừ ứ Ỡữ ự Ư Ừ Ứ Ử Ữ Ự "
+ "ì à ỉ Ä© ị ÃŒ à Ỉ Ĩ Ị ỳ ý á»· ỹ ỵ Ỳ à Ỷ Ỹ á»´ Ä‘ Ä "
+ "“ †– à ’ Á ÇŽ … aI";
var utf8Literals = utf8Literal.Split(' ');
var utf8Unicode = "à á ả ã ạ À Á Ả Ã Ạ â ầ ấ ẩ ẫ ậ Â Ầ Ấ Ẩ Ẫ Ậ ă ằ ắ ẳ ẵ ặ Ă Ằ Ắ Ẳ Ẵ Ặ "
+ "ò ó ỏ õ ọ Ò Ó Ỏ Õ Ọ ô ồ ố ổ ỗ ộ Ô Ồ Ố Ổ Ỗ Ộ ơ ờ ớ ở ỡ ợ Ơ Ờ Ớ Ở Ỡ Ợ "
+ "è é ẻ ẽ ẹ È É Ẻ Ẽ Ẹ ê ề ế ể ễ ệ Ê Ề Ế Ể Ễ Ệ "
+ "ù ú ủ ũ ụ Ù Ú Ủ Ũ Ụ ư ừ ứ ử ữ ự Ư Ừ Ứ Ử Ữ Ự "
+ "ì í ỉ ĩ ị Ì Í Ỉ Ĩ Ị ỳ ý ỷ ỹ ỵ Ỳ Ý Ỷ Ỹ Ỵ đ Đ "
+ "“ ” – Á ’ Đ ă á";
var utf8Unicodes = utf8Unicode.Split(' ');
var utf8UnicodeComposite = "à á ả ã ạ À Á Ả Ã Ạ â ầ ấ ẩ ẫ ậ Â Ầ Ấ Ẩ Ẫ Ậ ă ằ ắ ẳ ẵ ặ Ă Ằ Ắ Ẳ Ẵ Ặ "
+ "ò ó ỏ õ ọ Ò Ó Ỏ Õ Ọ ô ồ ố ổ ỗ ộ Ô Ồ Ố Ổ Ỗ Ộ ơ ờ ớ ở ỡ ợ Ơ Ờ Ớ Ở Ỡ Ợ "
+ "è é ẻ ẽ ẹ È É Ẻ Ẽ Ẹ ê ề ế ể ễ ệ Ê Ề Ế Ể Ễ Ệ "
+ "ù ú ủ ũ ụ Ù Ú Ủ Ũ Ụ ư ừ ứ ử ữ ự Ư Ừ Ứ Ử Ữ Ự "
+ "ì í ỉ ĩ ị Ì Í Ỉ Ĩ Ị ỳ ý ỷ ỹ ỵ Ỳ Ý Ỷ Ỹ Ỵ đ Đ "
+ "“ ” – Á ’ Đ ă á";
var utf8UnicodeComposites = utf8UnicodeComposite.Split(' ');
var ansi = "a a a a a A A A A A a a a a a a A A A A A A a a a a a a A A A A A A "
+ "o o o o o O O O O O o o o o o o O O O O O O o o o o o o O O O O O O "
+ "e e e e e E E E E E e e e e e e E E E E E E "
+ "u u u u u U U U U U u u u u u u U U U U U U "
+ "i i i i i I I I I I y y y y y Y Y Y Y Y d D "
+ "\" \" - A ' D a a";
var ansis = ansi.Split(' ');
var decimalUnicode = "à á ả ã ạ À Á Ả Ã Ạ â ầ ấ ẩ ẫ ậ Â Ầ Ấ Ẩ Ẫ Ậ ă ằ ắ ẳ ẵ ặ Ă Ằ Ắ Ẳ Ẵ Ặ "
+ "ò ó ỏ õ ọ Ò Ó Ỏ Õ Ọ ô ồ ố ổ ỗ ộ Ô Ồ Ố Ổ Ỗ Ộ ơ ờ ớ ở ỡ ợ Ơ Ờ Ớ Ở Ỡ Ợ "
+ "è é ẻ ẽ ẹ È É Ẻ Ẽ Ẹ ê ề ế ể ễ ệ Ê Ề Ế Ể Ễ Ệ "
+ "ù ú ủ ũ ụ Ù Ú Ủ Ũ Ụ ư ừ ứ ử ữ ự Ư Ừ Ứ Ử Ữ Ự "
+ "ì í ỉ ĩ ị Ì Í Ỉ Ĩ Ị ỳ ý ỷ ỹ ỵ Ỳ Ý Ỷ Ỹ Ỵ đ Đ "
+ "" " - à ' Đ ă   á";
var decimalUnicodes = decimalUnicode.Split(' ');
var tcvn3 = "µ ¸ ¶ · ¹ µ ¸ ¶ · ¹ © Ç Ê È É Ë ¢ Ç Ê È É Ë ¨ » ¾ ¼ ½ Æ ¡ » ¾ ¼ ½ Æ "
+ "ß ã á â ä ß ã á â ä « å è æ ç é ¤ å è æ ç é ¬ ê í ë ì î ¥ ê í ë ì î "
+ "Ì Ð Î Ï Ñ Ì Ð Î Ï Ñ ª Ò Õ Ó Ô Ö £ Ò Õ Ó Ô Ö "
+ "ï ó ñ ò ô ï ó ñ ò ô õ ø ö ÷ ù ¦ õ ø ö ÷ ù "
+ "× Ý Ø Ü Þ × Ý Ø Ü Þ ú ý û ü þ ú ý û ü þ ® § "
+ "“ ” – ¸ ’ § ¨ ¸";
var tcvn3s = tcvn3.Split(' ');
int decodeLength;
var result = @string.Trim();
// convert
switch (mode)
{
// UTF8 Literal to unicode
case 0:
decodeLength = utf8Unicodes.Length;
for (int index = 0; index < decodeLength; index++)
if (index < utf8Literals.Length)
result = result.Replace(utf8Literals[index], utf8Unicodes[index]);
break;
// Unicode to UTF8 Literal
case 1:
decodeLength = utf8Literals.Length;
for (int index = 0; index < decodeLength; index++)
result = result.Replace(utf8Unicodes[index], utf8Literals[index]);
break;
// Unicode to ANSI
case 2:
decodeLength = utf8Unicodes.Length;
for (int index = 0; index < decodeLength; index++)
if (index < ansis.Length)
result = result.Replace(utf8Unicodes[index], ansis[index]);
break;
// UTF8 Literal to ANSI
case 3:
decodeLength = utf8Literals.Length;
for (int index = 0; index < decodeLength; index++)
if (index < ansis.Length)
result = result.Replace(utf8Literals[index], ansis[index]);
break;
// Unicode to Decimal
case 4:
decodeLength = utf8Unicodes.Length;
for (int index = 0; index < decodeLength; index++)
if (index < decimalUnicodes.Length)
result = result.Replace(utf8Unicodes[index], decimalUnicodes[index]);
result = result.Replace("Ð", "D");
break;
// Unicode Composite to ANSI
case 5:
decodeLength = utf8UnicodeComposites.Length;
for (int index = 0; index < decodeLength; index++)
if (index < ansis.Length)
result = result.Replace(utf8UnicodeComposites[index], ansis[index]);
result = result.Replace("Ð", "D");
break;
// Decimal to Unicode
case 6:
decodeLength = decimalUnicodes.Length;
for (int index = 0; index < decodeLength; index++)
if (index < utf8Unicodes.Length)
result = result.Replace(decimalUnicodes[index], utf8Unicodes[index]);
break;
// TCVN3 to Unicode
case 7:
// first, convert to decimal
decodeLength = tcvn3s.Length;
for (int index = 0; index < decodeLength; index++)
if (!tcvn3s[index].Equals("") && index < decimalUnicodes.Length)
result = result.Replace(tcvn3s[index], decimalUnicodes[index]);
// and then, convert from decimal to unicode
decodeLength = decimalUnicodes.Length;
for (int index = 0; index < decodeLength; index++)
if (index < utf8Unicodes.Length)
result = result.Replace(decimalUnicodes[index], utf8Unicodes[index]);
break;
// Unicode to Composite Unicode
case 8:
decodeLength = utf8Unicodes.Length;
for (int index = 0; index < decodeLength; index++)
if (index < utf8UnicodeComposites.Length)
result = result.Replace(utf8Unicodes[index], utf8UnicodeComposites[index]);
break;
// Composite Unicode to Unicode
case 9:
decodeLength = utf8UnicodeComposites.Length;
for (int index = 0; index < decodeLength; index++)
if (index < utf8Unicodes.Length)
result = result.Replace(utf8UnicodeComposites[index], utf8Unicodes[index]);
break;
default:
break;
}
return result.Replace(" ", " ");
}
/// <summary>
/// Converts this Vietnamese string from UTF8 to Unicode
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string ConvertUTF8ToUnicode(this string @string)
=> @string.ConvertVietnamese(0);
/// <summary>
/// Converts this Vietnamese string from Unicode to UTF8
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string ConvertUnicodeToUTF8(this string @string)
=> @string.ConvertVietnamese(1);
/// <summary>
/// Converts this Vietnamese string from Unicode to ANSI
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string ConvertUnicodeToANSI(this string @string)
=> @string.ConvertVietnamese(2).ConvertVietnamese(5);
/// <summary>
/// Converts this Vietnamese string from Unicode to Decimal
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string ConvertUnicodeToDecimal(this string @string)
=> @string.ConvertVietnamese(4);
/// <summary>
/// Converts this Vietnamese string from Decimal to Unicode
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string ConvertDecimalToUnicode(this string @string)
=> @string.ConvertVietnamese(6);
/// <summary>
/// Converts this Vietnamese string from TCVN3 to Unicode
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string ConvertTCVN3ToUnicode(this string @string)
=> @string.ConvertVietnamese(7);
/// <summary>
/// Converts this Vietnamese string from Pre-composed Unicode to Composite Unicode
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string ConvertUnicodeToCompositeUnicode(this string @string)
=> @string.ConvertVietnamese(8);
/// <summary>
/// Converts this Vietnamese string from Composite Unicode to Pre-composed Unicode
/// </summary>
/// <param name="string"></param>
/// <returns></returns>
public static string ConvertCompositeUnicodeToUnicode(this string @string)
=> @string.ConvertVietnamese(9);
#endregion
#region Conversions (Uri)
static Regex URICharacters { get; } = new Regex("[^a-zA-Z0-9_-]+");
static Regex URICharactersWithDot { get; } = new Regex("[^a-zA-Z0-9._-]+");
/// <summary>
/// Generates the ANSI uri from this string (means remove all white spaces and special characters)
/// </summary>
/// <param name="string"></param>
/// <param name="toLowerCase">true to return lower case</param>
/// <param name="allowDotSymbols">true to allow dot symbols (.)</param>
/// <param name="allowEmpty">true to allow empty (default is false - will be updated as a random value)</param>
/// <returns></returns>
public static string GetANSIUri(this string @string, bool toLowerCase = true, bool allowDotSymbols = false, bool allowEmpty = false)
{
// convert Vietnamese characters
var result = @string.Trim().ConvertUnicodeToANSI();
// remove all special characters
result = result.Replace(StringComparison.OrdinalIgnoreCase, "C#", "CSharp").Replace(StringComparison.OrdinalIgnoreCase, "F#", "FSharp").Replace(StringComparison.OrdinalIgnoreCase, "Q#", "QSharp").Replace(" ", "-");
result = allowDotSymbols
? StringService.URICharactersWithDot.Replace(result, "")
: StringService.URICharacters.Replace(result, "");
// remove duplicate characters
while (result.Contains("--"))
result = result.Replace("--", "-");
while (result.Contains("__"))
result = result.Replace("__", "_");
// normalize first & last characters
while (result.StartsWith("-") || result.StartsWith("_"))
result = result.Right(result.Length - 1);
while (result.EndsWith("-") || result.EndsWith("_"))
result = result.Left(result.Length - 1);
// add timestamp if has no value
if (result.Equals("") && !allowEmpty)
result = "v" + DateTime.Now.ToUnixTimestamp();
// numeric
else if (result.IsNumeric())
result = "v" + DateTime.Now.ToUnixTimestamp() + result;
return toLowerCase
? result.ToLower()
: result;
}
/// <summary>
/// Validate the ANSI uri
/// </summary>
/// <param name="ansiUri">The string that presents an ANSI uri to check</param>
/// <param name="allowDotSymbols">true to allow dot symbols (.)</param>
/// <returns>true if valid; otherwise false.</returns>
public static bool IsValidANSIUri(this string ansiUri, bool allowDotSymbols = false)
=> !string.IsNullOrWhiteSpace(ansiUri) && ansiUri.IsEquals(allowDotSymbols ? StringService.URICharactersWithDot.Replace(ansiUri, "") : StringService.URICharacters.Replace(ansiUri, ""));
#endregion
}
}