-
Notifications
You must be signed in to change notification settings - Fork 1
/
StringUtil.cs
373 lines (338 loc) · 12.1 KB
/
StringUtil.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
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace DotStd
{
/// <summary>
/// String and char util functions.
/// </summary>
public static class StringUtil
{
public const string _NoErrorMsg = ""; // "" = Success = no error. null = did nothing.
// ToByteArray = byte[] = System.Text.Encoding.Default.GetBytes(sIn);
public static int CompareNoCase(this string s1, string s2)
{
// simple Wrapper
return string.Compare(s1, s2, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// return one string or the other. https://en.wikipedia.org/wiki/IIf
/// </summary>
/// <param name="expr"></param>
/// <param name="ifTrue"></param>
/// <param name="ifFalse"></param>
/// <returns></returns>
public static string IIf(bool expr, string ifTrue, string ifFalse = "")
{
if (expr)
return ifTrue;
return ifFalse;
}
/// <summary>
/// is this char a basic number? like Regex regexDigit = new Regex("[^0-9]");
/// NOT extended ASCII, 1/2 etc.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static bool IsDigit1(char ch)
{
#if false // false true
return ch >= '0' && ch <= '9';
#else
return char.IsDigit(ch); // NOT char.IsNumber
#endif
}
/// <summary>
/// is this char basic upper case? like new Regex("[^A-Z]");
/// NOT extended ASCII. Latin only.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static bool IsUpper1(char ch)
{
#if true // false true
return (ch >= 'A' && ch <= 'Z');
#else
return char.IsUpper(ch);
#endif
}
/// <summary>
/// is this char basic lower case? like new Regex("[^a-z]");
/// NOT extended ASCII. Latin only.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static bool IsLower1(char ch)
{
#if true // false true
return (ch >= 'a' && ch <= 'z');
#else
return char.IsLower(ch);
#endif
}
/// <summary>
/// Is Alpha?
/// NOT extended ASCII. Latin only.
/// new Regex("[^a-zA-Z]");
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static bool IsAlpha1(char ch)
{
#if true // false true
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
#else
return char.IsLetter(ch);
#endif
}
public static bool IsAlphaNumeric1(char ch)
{
// NOT extended ASCII. Latin only.
// Regex("[^a-zA-Z0-9]")
#if true // false true
return IsAlpha1(ch) || IsDigit1(ch);
#else
return char.IsLetterOrDigit(ch);
#endif
}
public const string kVowels = "aeiouAEIOU";
public static bool IsVowel(char ch)
{
return kVowels.Contains(ch);
}
public static bool HasUpperCase([NotNullWhen(true)] string? str)
{
// IsUpper for extended ASCII
return !string.IsNullOrEmpty(str) && str.Any(c => char.IsUpper(c));
}
public static bool HasLowerCase([NotNullWhen(true)] string? str)
{
// IsLower for extended ASCII
return !string.IsNullOrEmpty(str) && str.Any(c => char.IsLower(c));
}
public static bool HasNumber([NotNullWhen(true)] string? str)
{
// allow extended IsNumber for 1/2 etc
return !string.IsNullOrEmpty(str) && str.Any(c => char.IsNumber(c));
}
public static bool IsNumeric1([NotNullWhen(true)] string? str)
{
// Does this string contain a simple/strict integer number? no spaces, -+ or .
// NOT extended IsNumber 1/2
if (string.IsNullOrWhiteSpace(str))
return false;
return str.All(c => IsDigit1(c));
}
static readonly Lazy<Regex> _regexNum2 = new(() => new Regex(@"^\s*\-?\d+(\.\d+)?\s*$"));
public static bool IsNumeric2([NotNullWhen(true)] string? str)
{
// Far more forgiving IsNumeric(). allow leading spaces. points. signs.
// NOT extended IsNumber 1/2. No decimal comma for European?
if (string.IsNullOrWhiteSpace(str))
return false;
return _regexNum2.Value.IsMatch(str);
}
public static bool IsAlphaNumeric1([NotNullWhen(true)] string? str)
{
// _regexAlNum = new Regex("[^a-zA-Z0-9]");
// NOT extended ASCII. Latin only.
if (string.IsNullOrWhiteSpace(str))
return false;
return str.All(c => IsAlphaNumeric1(c));
}
[return: NotNullIfNotNull("sValue")]
public static string? GetNumericOnly(string? sValue, bool bStopOnNonNumeric = false)
{
// filter out all non numeric chars. For telephone numbers?
// NOT extended ASCII. Latin only.
// AKA ToNumStr
// return System.Text.RegularExpressions.Regex.Replace(sValue,"[^\d]", ""); or Regex.Replace(sValue, "[^0-9]", "")
if (sValue == null)
return null;
if (string.IsNullOrWhiteSpace(sValue))
return "";
int nLen = sValue.Length;
var sb = new StringBuilder();
for (int i = 0; i < nLen; i++)
{
char ch = sValue[i];
if (IsDigit1(ch))
{
sb.Append(ch);
}
else if (bStopOnNonNumeric)
break;
}
return sb.ToString();
}
public static string GetAlphaNumericOnly(string? sValue)
{
// filter out all non alpha numeric chars.
// NOT extended ASCII. Latin only.
// For comparing DLNum etc.
// System.Text.RegularExpressions.Regex.Replace(sDL, "[^A-Za-z0-9]", "")
// AKA ToAlNum
if (string.IsNullOrWhiteSpace(sValue))
return "";
return System.Text.RegularExpressions.Regex.Replace(sValue, "[^A-Za-z0-9]", "");
}
public static bool IsWildcardMatch([NotNullWhen(true)] string? wildcardPattern, string subject)
{
// Simple wildcard match
// https://www.hiimray.co.uk/2020/04/18/implementing-simple-wildcard-string-matching-using-regular-expressions/474
if (string.IsNullOrWhiteSpace(wildcardPattern))
{
return false;
}
string newWildcardPattern = wildcardPattern.Replace("*", "");
int wildcardCount = wildcardPattern.Length - newWildcardPattern.Length;
if (wildcardCount <= 0)
{
return subject.Equals(wildcardPattern, StringComparison.CurrentCultureIgnoreCase);
}
else if (wildcardCount == 1)
{
if (wildcardPattern.StartsWith("*"))
{
return subject.EndsWith(newWildcardPattern, StringComparison.CurrentCultureIgnoreCase);
}
else if (wildcardPattern.EndsWith("*"))
{
return subject.StartsWith(newWildcardPattern, StringComparison.CurrentCultureIgnoreCase);
}
}
string regexPattern = string.Concat("^", Regex.Escape(wildcardPattern).Replace("\\*", ".*"), "$");
try
{
return Regex.IsMatch(subject, regexPattern);
}
catch
{
return false;
}
}
/// <summary>
/// trim a string for whitespace but ignore null.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
[return: NotNullIfNotNull("s")]
public static string? TrimN(string? s)
{
if (s == null)
return s;
return s.Trim();
}
public static int CompareSub(string s, int i, string sub, int len)
{
for (int j = 0; j < len; j++)
{
char ch1 = s[i + j];
char ch2 = sub[j];
if (ch1 != ch2)
{
return ch1 - ch2;
}
}
return 0;
}
public static int CountSub(string s, string sub)
{
// count occurrences of sub in s.
int lenSub = sub.Length;
if (lenSub <= 0)
return 0;
int count = 0;
int len = s.Length - lenSub;
for (int i = 0; i <= len; i++)
{
if (CompareSub(s, i, sub, lenSub) == 0)
count++;
}
return count;
}
/// Get a substring but never throw.
[return: NotNullIfNotNull("s")]
public static string? SubSafe(string? s, int i, int lenTake = short.MaxValue)
{
if (s == null)
return null;
if (i < 0)
{
lenTake += i;
i = 0;
}
int lenMax = s.Length;
if (i >= lenMax || lenTake <= 0) // take nothing
return "";
lenMax -= i;
if (lenTake > lenMax)
lenTake = lenMax;
return s.Substring(i, lenTake);
}
[return: NotNullIfNotNull("s")]
public static string? Truncate(string? s, int size)
{
// Left len chars.
// Take X chars and lose the rest. No padding.
// AKA Left() in Strings (VB)
ValidState.ThrowIfNegative(size, nameof(size));
if (s == null)
return null;
if (s.Length > size)
return s.Substring(0, size);
return s; // no truncate or padding.
}
[return: NotNullIfNotNull("s")]
public static string? Ellipsis(this string? s, int lenMax = 0x400)
{
// Truncate string with ellipsis.
ValidState.ThrowIfNegative(lenMax, nameof(lenMax));
if (s == null)
return null;
if (s.Length > lenMax)
return s.Substring(0, lenMax) + "...";
return s;
}
[return: NotNullIfNotNull("s")]
public static string? TruncateRight(this string? s, int size)
{
// right len chars.
// Take X chars and lose the rest. No padding.
// AKA Right() in Strings (VB)
ValidState.ThrowIfNegative(size, nameof(size));
if (s == null)
return null;
if (s.Length > size)
return s.Substring(s.Length - size);
return s; // no truncate or padding.
}
public static string FieldLeft(string s, int size, char paddingChar = ' ')
{
// Left aligned field that is cropped or padded with spaces to exact size.
if (s == null)
return new string(paddingChar, size);
else if (s.Length > size)
return s.Substring(0, size);
else
return s.PadRight(size, paddingChar);
}
public static string FieldRight(string s, int size, char paddingChar = ' ')
{
// Right aligned field that is cropped or padded with spaces to exact size.
if (s == null)
return new string(paddingChar, size);
else if (s.Length > size)
return s.Substring(s.Length - size, size);
else
return s.PadLeft(size, paddingChar); // PadLeft doesn't truncate
}
public static string LeadZero(string s, int size)
{
// Right aligned. Add leading zeros
return FieldRight(s, size, '0');
}
}
}