-
Notifications
You must be signed in to change notification settings - Fork 2
/
StringUtils.xojo_code
2672 lines (2236 loc) · 84.3 KB
/
StringUtils.xojo_code
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#tag Module
Protected Module StringUtils
#tag Method, Flags = &h1
Protected Function Chop(s As String, charsToCut As Integer) As String
// Return s with the rightmost 'charsToCut' chars removed.
Dim charsLeft As Integer = s.Len - charsToCut
if charsLeft <= 0 then return ""
return s.Left( s.Len - charsToCut )
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function Chop(s As String, stringToCut As String) As String
// Chops 'stringToCut' off of s, if stringToCut is found at the end.
// Useful for removing file extensions, trailing punctuation, etc.
Dim cutLen As Integer = stringToCut.Len
if Right(s, cutLen) = stringToCut then
return s.Left( s.Len - cutLen )
else
return s
end if
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function ChopB(s As String, bytesToCut As Integer) As String
// Return s with the rightmost 'bytesToCut' bytes removed.
Dim bytesLeft As Integer = s.LenB - bytesToCut
if bytesLeft <= 0 then return ""
return s.LeftB( s.LenB - bytesToCut )
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function ChopB(s As String, stringToCut As String) As String
// Chops 'stringToCut' off of s, if stringToCut is found at the end.
// Useful for removing file extensions, trailing punctuation, etc.
Dim cutLenB As Integer = stringToCut.LenB
if StrComp( RightB(s, cutLenB), stringToCut, 0 ) = 0 then
return s.LeftB( s.LenB - cutLenB )
else
return s
end if
End Function
#tag EndMethod
#tag Method, Flags = &h0
Function Contains(extends s As String, what As String) As Boolean
// Return true if 's' contains the substring 'what'.
// By "contains" we mean case-insensitive, encoding-savvy containment
// as with InStr.
if what = "" then return true
return InStr( s, what ) > 0
End Function
#tag EndMethod
#tag Method, Flags = &h0
Function ContainsB(extends s As String, what As String) As Boolean
// Return true if 's' contains the substring 'what'.
// By "contains" we mean binary containment
// as with InStrB.
if what = "" then return true
return InStrB( s, what ) > 0
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function ControlCharacters() As String
// Return the control character region of the ASCII set,
// i.e., ASCII 0 through 31.
Dim i As Integer
if mControlChars = "" then
for i = 0 to 31
mControlChars = mControlChars + Encodings.ASCII.Chr(i)
next
end if
return mControlChars
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function Count(source As String, substr As String) As Integer
// Return how many non-overlapping occurrences of 'substr' there
// are in 'source'.
dim theCount as Integer
dim substrLength as Integer
dim start as Integer
substrLength = Len(substr)
if substrLength = 0 then return Len(source) + 1
start = 1
Do
start= InStr(start, source, substr)
If start < 1 then return theCount
theCount = theCount + 1
start = start + substrLength
Loop
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function CountB(source As String, substr As String) As Integer
// Return how many non-overlapping occurrences of 'substr' there
// are in 'source', doing binary comparison.
dim theCount as Integer
dim substrLength as Integer
dim start as Integer
substrLength = Len(substr)
if substrLength = 0 then return LenB(source) + 1
start = 1
Do
start= InStrB(start, source, substr)
If start < 1 then return theCount
theCount = theCount + 1
start = start + substrLength
Loop
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function CountFieldsQuoted(src as string, sep as string) As integer
// Equivalent to RB's CountFields() function, but respects quoted values
// Usage:
// s = """Hello, Kitty"", ""One"", ""Two, Three"""
// x = CountFieldsQuoted(s, ",")
// result: x=3
#pragma DisableBoundsChecking
#pragma NilObjectChecking false
if InStr( src, sep ) = 0 then return 1
if InStr(src,"""")=0 then return CountFields(src, sep)
dim countParts, i, n, c as integer
dim sepLen as integer = len( sep )
dim parts( -1 ) as string
parts = split( src, """" )
countParts = UBound( parts )
for i = 0 to countParts step 2
n = InStr( parts( i ), sep )
while n > 0
c = c + 1
n = InStr( n + sepLen, parts( i ), sep )
wend
next i
return c + 1
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function CountRegEx(s As String, pattern As String) As Integer
// Count the number of occurrences of a RegEx pattern within a string.
Dim out As Integer
Dim re As New RegEx
Dim rm As RegExMatch
re.SearchPattern = pattern
rm = re.Search( s )
while rm <> nil
'System.DebugLog rm.SubExpressionString(0) + " at " + str(rm.SubExpressionStartB(0)) + " matches " + pattern + " in " + s
out = out + 1
rm = re.Search
wend
return out
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function DecimalSeparator() As String
// Return the decimal separator the user uses (either "." or ",").
if mDecimalSeparator = "" then
mDecimalSeparator = Format(1.2, "0.0")
mDecimalSeparator = Mid( mDecimalSeparator, 2, 1 )
end if
return mDecimalSeparator
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function DecodeCase(s As String) As String
// This function undoes the encoding of case done by EncodeCase, resulting
// in the original string.
Dim parts() As String = Split( s, "^" )
for i As Integer = 1 to UBound( parts ) step 2
if parts(i) = "" then
parts(i) = "^"
else
parts(i) = Uppercase( parts(i) )
end if
next
return Join( parts, "" )
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function EditDistance(s1 As String, s2 As String) As Integer
// Return the Levenshtein distance, aka the edit distance,
// between the two StringUtils. That's the number of insertions,
// deletions, or changes required to make one string match the other.
// A result of 0 means the strings
// are identical; higher values mean more different.
// Note that this function is case-sensitive; if you want a case-
// insensitive measure, simply Uppercase or Lowercase both strings
// before calling.
// Implementation adapted from <http://www.merriampark.com/ld.htm>,
// though we're using only a 1D array since the 2D array is wasteful.
#pragma DisableBackgroundTasks
#pragma DisableBoundsChecking
#pragma DisableAutoWaitCursor
Dim n, m As Integer
n = s1.Len
m = s2.Len
if n = 0 then return m
if m = 0 then return n
Dim i, j, cost As Integer
Dim d(-1) As Integer
Redim d(m)
for j = 1 to m
d(j) = j
next
Dim s1chars(-1), s2chars(-1) As String
s1chars = Split( s1, "" )
s2chars = Split( s2, "" )
Dim s1char As String
Dim lastCost, nextCost As Integer
Dim a, b, c As Integer
Dim jMinus1 As Integer
for i = 1 to n
s1char = s1chars(i-1)
lastCost = i
jMinus1 = 0
for j = 1 to m
if StrComp(s1char, s2chars(jMinus1),0) = 0 then cost = 0 else cost = 1
// set nextCost to the minimum of the following three possibilities:
a = d(j) + 1
b = lastCost + 1
c = cost + d(jMinus1)
if a < b then
if c < a then nextCost = c else nextCost = a
else
if c < b then nextCost = c else nextCost = b
end if
d(jMinus1) = lastCost
lastCost = nextCost
jMinus1 = j
next
d(m) = lastCost
next
return nextCost
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function EncodeCase(s As String) As String
// Return a version of the given string that encodes the uppercase/lowercase state
// of each letter as follows: every time we switch from uppercase to lowercase, we
// insert a "^". A "^" in the original string will be represented as "^^". Finally, we
// will assume lowercase at the beginning of the string (so an initial capital letter
// will be preceded by "^").
//
// This can be useful for doing things like case-sensitive lookup of strings in a
// Dictionary, which is normally case insensitive.
//
// For the inverse operation, see DecodeCase.
Dim chars() As String = Split( s, "" )
Dim inUpperState As Boolean = false
Dim idx As Integer
Dim anyUpper As Boolean
for idx = 0 to UBound( chars )
Dim c As String = chars(idx)
if c = "^" then
// got a caret in the original string; double it
chars.Insert idx, "^"
idx = idx + 1
else
// determine whether the given character fails to match the current state
Dim codepoint As Integer = Asc(c)
Dim switchCase As Boolean
if inUpperState then
if codepoint < 128 then
// lowercase ASCII ranges from 97 to 122
switchCase = (codepoint >= 97 and codepoint <= 122)
else
// if not ASCII, use RB's routines to see if it'd be any different in upper case
switchCase = StrComp( c, Uppercase(c), 0 ) <> 0
end if
else
if codepoint < 128 then
// uppercase ASCII ranges from 65 to 90
switchCase = (codepoint >= 65 and codepoint <= 90)
else
// if not ASCII, use RB's routines to see if it'd be any different in lower case
switchCase = StrComp( c, Lowercase(c), 0 ) <> 0
end if
if switchCase then anyUpper = true
end if
if switchCase then
// yep, time to switch case
chars.Insert idx, "^"
idx = idx + 1
inUpperState = not inUpperState
end if
end if
next
Dim result As String = Join( chars, "" )
if anyUpper then result = Lowercase( result )
return result
End Function
#tag EndMethod
#tag Method, Flags = &h0
Function EndsWith(extends s As String, withWhat As String) As Boolean
// Return true if 's' ends with the string 'withWhat',
// doing a standard string comparison.
return Right(s, withWhat.Len) = withWhat
End Function
#tag EndMethod
#tag Method, Flags = &h0
Function EndsWithB(extends s As String, withWhat As String) As Boolean
// Return true if 's' ends with the string 'withWhat',
// doing a binary comparison.
return StrComp( RightB(s, withWhat.LenB), withWhat, 0 ) = 0
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function GuessEncoding(s As String) As TextEncoding
// Guess what text encoding the text in the given string is in.
//
// Note that it this version does not report whether the UTF-32 or
// UTF-16 that is in the wrong byte order. If that's a possibility,
// you should use the other version of GuessEncoding instead.
Dim whoCares As Boolean
return StringUtils.GuessEncoding( s, whoCares )
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function GuessEncoding(s As String, ByRef outWrongOrder As Boolean) As TextEncoding
// Guess what text encoding the text in the given string is in.
// This ignores the encoding set on the string, and guesses
// one of the following:
//
// * UTF-32
// * UTF-16
// * UTF-8
// * Encodings.SystemDefault
//
// If the UTF-32 or UTF-16 is in the wrong byte order for this platform,
// then outWrongOrder will be set to true.
static isBigEndian, endianChecked As Boolean
if not endianChecked then
Dim temp As String = Encodings.UTF16.Chr( &hFEFF )
isBigEndian = (AscB( MidB( temp, 1, 1 ) ) = &hFE)
endianChecked = true
end if
// check for a BOM
Dim b0 As Integer = AscB( s.MidB( 1, 1 ) )
Dim b1 As Integer = AscB( s.MidB( 2, 1 ) )
Dim b2 As Integer = AscB( s.MidB( 3, 1 ) )
Dim b3 As Integer = AscB( s.MidB( 4, 1 ) )
if b0=0 and b1=0 and b2=&hFE and b3=&hFF then
// UTF-32, big-endian
outWrongOrder = not isBigEndian
return Encodings.UTF32BE
elseif b0=&hFF and b1=&hFE and b2=0 and b3=0 and s.LenB >= 4 then
// UTF-32, little-endian
outWrongOrder = isBigEndian
return Encodings.UTF32LE
elseif b0=&hFE and b1=&hFF then
// UTF-16, big-endian
outWrongOrder = not isBigEndian
return Encodings.UTF16
elseif b0=&hFF and b1=&hFE then
// UTF-16, little-endian
outWrongOrder = isBigEndian
return Encodings.UTF16
elseif b0=&hEF and b1=&hBB and b1=&hBF then
// UTF-8 (ah, a sensible encoding where endianness doesn't matter!)
return Encodings.UTF8
end if
// no BOM; see if it's entirely ASCII.
Dim m As MemoryBlock = s
Dim i, maxi As Integer = s.LenB - 1
for i = 0 to maxi
if m.Byte(i) > 127 then exit
next
if i > maxi then return Encodings.ASCII
// Not ASCII; check for a high incidence of nulls every other byte,
// which suggests UTF-16 (at least in Roman text).
Dim nulls(1) As Integer // null count in even (0) and odd (1) bytes
for i = 0 to maxi
if m.Byte(i) = 0 then
nulls(i mod 2) = nulls(i mod 2) + 1
end if
next
if nulls(0) > nulls(1)*2 and nulls(0) > maxi\2 then
// UTF-16, big-endian
outWrongOrder = not isBigEndian
return Encodings.UTF16
elseif nulls(1) > nulls(0)*2 and nulls(1) > maxi\2 then
// UTF-16, little-endian
outWrongOrder = isBigEndian
return Encodings.UTF16
end if
// it's not ASCII; check for illegal UTF-8 characters.
// See Table 3.1B, "Legal UTF-8 Byte Sequences",
// at <http://unicode.org/versions/corrigendum1.html>
Dim b As Byte
for i = 0 to maxi
select case m.Byte(i)
case &h00 to &h7F
// single-byte character; just continue
case &hC2 to &hDF
// one additional byte
if i+1 > maxi then exit for
b = m.Byte(i+1)
if b < &h80 or b > &hBF then exit for
i = i+1
case &hE0
// two additional bytes
if i+2 > maxi then exit for
b = m.Byte(i+1)
if b < &hA0 or b > &hBF then exit for
b = m.Byte(i+2)
if b < &h80 or b > &hBF then exit for
i = i+2
case &hE1 to &hEF
// two additional bytes
if i+2 > maxi then exit for
b = m.Byte(i+1)
if b < &h80 or b > &hBF then exit for
b = m.Byte(i+2)
if b < &h80 or b > &hBF then exit for
i = i+2
case &hF0
// three additional bytes
if i+3 > maxi then exit for
b = m.Byte(i+1)
if b < &h90 or b > &hBF then exit for
b = m.Byte(i+2)
if b < &h80 or b > &hBF then exit for
b = m.Byte(i+3)
if b < &h80 or b > &hBF then exit for
i = i+3
case &hF1 to &hF3
// three additional bytes
if i+3 > maxi then exit for
b = m.Byte(i+1)
if b < &h80 or b > &hBF then exit for
b = m.Byte(i+2)
if b < &h80 or b > &hBF then exit for
b = m.Byte(i+3)
if b < &h80 or b > &hBF then exit for
i = i+3
case &hF4
// three additional bytes
if i+3 > maxi then exit for
b = m.Byte(i+1)
if b < &h80 or b > &h8F then exit for
b = m.Byte(i+2)
if b < &h80 or b > &hBF then exit for
b = m.Byte(i+3)
if b < &h80 or b > &hBF then exit for
i = i+3
else
exit for
end select
next i
if i > maxi then return Encodings.UTF8 // no illegal UTF-8 sequences, so that's probably what it is
// If not valid UTF-8, then let's just guess the system default.
return Encodings.SystemDefault
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function Hash(s As String) As Integer
// Return the hash value of the given string, as used by RB's
// Variant and Dictionary classes.
Dim v As Variant
v = s
return v.Hash
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function HexB(s As String) As String
// Return a hex representation of each byte of s,
// i.e., each byte becomes a pair of hexadecimal digits,
// separated by spaces from the next byte.
// Credit: Charles Yeomans.
if s = "" then return ""
#if RBVersion > 5.5
Static HexTable as MemoryBlock
#else
Dim HexTable as MemoryBlock
#endif
if HexTable Is Nil then
HexTable = new MemoryBlock(512)
For i as Integer = 0 to 15
HexTable.StringValue(i + i , 2) = "0" + Hex(i)
Next
For i as Integer = 16 to 255
HexTable.StringValue(i + i, 2) = Hex(i)
Next
end if
dim inData as MemoryBlock = new MemoryBlock(LenB(s))
inData.StringValue(0, inData.Size) = s
dim outData as MemoryBlock = new MemoryBlock(3*inData.Size - 1)
outData.Short(0) = HexTable.Short(2*inData.Byte(0))
dim lastByte as Integer = inData.Size - 1
For offset as Integer = 1 to lastByte
outData.Byte(3*offset - 1) = 32 // (space)
outData.Short(3*offset) = HexTable.Short(2*inData.Byte(offset))
Next
Return outData.StringValue(0, outData.Size, Encodings.ASCII)
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function InStrQuoted(start As Integer = 1, source As String, find As String) As Integer
// This is the same as the built-in InStr function, except that it ignores
// any occurrence of "find" within double quotes.
do
// Find the next occurrence of the search string. If none, then we're done.
Dim foundPos As Integer = InStr( start, source, find )
if foundPos < 1 then return foundPos
// Now, also find the next quotation mark; if this comes before
// our foundPos, then we need to ignore that and resume searching
// after the closing quote. Otherwise, we're done.
Dim quotePos As Integer = InStr( start, source, """" )
if quotePos = 0 or quotePos > foundPos then return foundPos
Dim closeQuotePos As Integer = InStr( quotePos+1, source, """" )
if closeQuotePos = 0 then return 0 // no closing quote, treat whole end of string as quoted
start = closeQuotePos + 1
loop
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function InStrReverse(startPos As Integer = - 1, source As String, substr As String) As Integer
// Similar to InStr, but searches backwards from the given position
// (or if startPos = -1, then from the end of the string).
// If substr can't be found, returns 0.
Dim srcLen As Integer = source.Len
if startPos = -1 then startPos = srcLen
// Here's an easy way...
// There may be a faster implementation, but then again, there may not -- it probably
// depends on the particulars of the data.
Dim reversedSource As String = Reverse(source)
Dim reversedSubstr As String = Reverse(substr)
Dim reversedPos As Integer
reversedPos = InStr( srcLen - startPos + 1, reversedSource, reversedSubstr )
if reversedPos < 1 then return 0
return srcLen - reversedPos - substr.Len + 2
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function InStrReverseB(startPosB As Integer = - 1, source As String, substr As String) As Integer
// Similar to InStrB, but searches backwards from the given position
// (or if startPosB = -1, then from the end of the string).
// If substr can't be found, returns 0.
Dim srcLen As Integer = source.LenB
Dim subLen As Integer = substr.LenB
if startPosB = -1 then startPosB = srcLen
// We'll do a simple sequential search. A Boyer-Moore algorithm
// would work better in many cases, but we'd have to rewrite the
// whole algorithm to work backwards. The sequential search will
// be good enough in most cases anyway.
Dim posB As Integer
for posB = Min( srcLen - subLen + 1, startPosB ) downTo 1
if StrComp( MidB( source, posB, subLen ), substr, 0 ) = 0 then return posB
next posB
return 0
End Function
#tag EndMethod
#tag Method, Flags = &h0
Function IsEmpty(extends s As String) As Boolean
// Return true if the string is empty.
return s = ""
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function JoinQuoted(fields() as String, delimiter as String) As String
// Join the given strings with a delimiter, just like RB's intrinsic Join
// method, except that if any of the fields contains the delimiter,
// that item will be surrounded by quotes in the output. See
// SplitQuoted for the inverse function.
// Approach: copy the items into a second array, putting quotes
// around any that contain the delimiter, then Join them. This
// way we don't mutate the array that's passed in.
Dim quoted() As String
Dim ub As Integer = UBound( fields )
Redim quoted( ub )
for i As Integer = 0 to ub
Dim fld As String = fields(i)
if Instr( fld, Delimiter ) > 0 then
quoted(i) = """" + fld + """"
else
quoted(i) = fld
end if
next
return Join( quoted, delimiter )
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function LineEnding(s As String) As String
// Return the first line ending (of any standard sort: Unix, classic Mac, or Windows)
// which is found in the given string. If none is found, return standard EndOfLine
// for the platform we're running on.
// The code below can't deal with UTF-16, but should deal fine with anything else.
// So, in those rare cases where we have UTF-16, let's convert. This could be a
// performance bottleneck if you call this on large UTF-16 strings.
if s.Encoding = Encodings.UTF16 then s = s.ConvertEncoding( Encodings.UTF8 )
// Loop over the bytes of the string until we find a 13 or 10. A line ending should
// be either 13 alone (Mac), 10 alone (Unix), or 13+10 (Windows).
Dim posB, maxPosB As Integer
maxPosB = LenB( s )
for posB = 1 to maxPosB
Dim b As Integer = AscB( MidB( s, posB, 1 ) )
if b = 10 then
return Chr(10)
elseif b = 13 then
if AscB( MidB( s, posB+1, 1 ) ) = 10 then return Chr(13) + Chr(10)
return Chr(13)
end if
next
return EndOfLine
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function LTrim(source As String, charsToTrim As String) As String
// This is an extended version of RB's LTrim function that lets you specify
// a set of characters to trim.
Dim srcLen As Integer = source.Len
Dim leftPos, i As Integer
for i = 1 to srcLen
if InStr( charsToTrim, Mid(source, i, 1) ) = 0 then exit
next
leftPos = i
if leftPos > srcLen then return ""
return Mid( source, leftPos )
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Function MatchCase(textToChange As String, sampleText As String) As String
// Return a version of textToChange that matches the case style
// of sampleText: Lowercase, Uppercase, or Titlecase.
// Examine the text until we find 2 characters that have case.
Dim pos As Integer = 1
Dim maxPos As Integer = sampleText.Len
Dim foundUpper() As Boolean
Dim c, upperC, lowerC As String
for pos = 1 to maxPos
c = MidB( sampleText, pos, 1 )
upperC = Uppercase(c)
lowerC = Lowercase(c)
if StrComp( upperC, lowerC, 0 ) <> 0 then
// found a character with case; remember which case it is
foundUpper.Append StrComp(c, upperC, 0 ) = 0
if UBound( foundUpper ) >= 1 then exit
else
// found a caseless character; reset our found list
Redim foundUpper(-1)
end if
next
if UBound( foundUpper ) < 1 then
// didn't find enough characters with case; sample is no good
return textToChange
end if
if foundUpper(0) then
if foundUpper(1) then return Uppercase(textToChange)
return Titlecase(textToChange)
end if
return Lowercase(textToChange)
End Function
#tag EndMethod
#tag Method, Flags = &h1
Protected Sub Metaphone(source As String, ByRef outPrimary As String, ByRef outAlternate As String)
// Compute the Double Metaphone of the source string. This is an algorithm that
// finds one or two approximate phonetic representations of a string, useful in
// searching for almost-matches -- e.g., looking for names whose spelling may have
// varied, or correcting typos made by the user, and so on.
//
// The output is roughly human-readable, with the following conventions:
// Vowels are omitted from the output, except for a vowel at the beginning
// of a word, which is represented by an A (e.g. "ox" becomes "AKS")
// X is used to represent a "ch" sound (e.g., "church" becomes "XRX")
// 0 (zero) is used to represent a "th" sound (e.g. "think" becomes "0NK")
//
// For more information about Double Metaphone, see:
// http://aspell.sourceforge.net/metaphone/
// http://www.cuj.com/articles/2000/0006/0006d/0006d.htm?topic=articles
//
// This implementation is based on the one at:
// http://aspell.sourceforge.net/metaphone/dmetaph.cpp
Dim length As Integer
length = source.Len
if length < 1 then
outPrimary = ""
outAlternate = ""
return
end if
source = Uppercase(source) + " "
Dim current As Integer = 1
Dim charAt(-1) As String
charAt = source.Split("")
charAt.Insert 0, "" // (make it 1-based, like Mid)
Dim slavoGermanic As Boolean
if InStr(source, "W") > 0 or InStr(source, "K") > 0 _
or InStr(source, "CZ") > 0 or InStr(source, "WITZ") > 0 then
slavoGermanic = true
end if
Dim out1, out2 As String
// skip these when at start of word
if MStringAt(source, 1, 2, "GN", "KN", "PN", "WR", "PS") then current = current + 1
// initial 'X' is pronounced 'Z' e.g. 'Xavier'
if charAt(1) = "X" then
out1 = out1 + "S"
out2 = out2 + "S" // "Z" maps to "S"
current = current + 1
end if
//---------- main loop ---------------
while current <= length
select case charAt(current)
case "A", "E", "I", "O", "U", "Y"
if current = 1 then
// all initial vowels map to "A"; elsewhere they're skipped
out1 = out1 + "A"
out2 = out2 + "A"
end if
current = current + 1
case "B"
//"-mb", e.g", "dumb", already skipped over...
out1 = out1 + "P"
out2 = out2 + "P"
if charAt(current + 1) = "B" then
current = current + 2
else
current = current + 1
end if
case "Ç"
out1 = out1 + "S"
out2 = out2 + "S"
current = current + 1
case "C"
// various germanic
if current > 2 _
and not MIsVowel(source, current - 2) _
and MStringAt(source, (current - 1), 3, "ACH") _
and (charAt(current + 2) <> "I" and (charAt(current + 2) <> "E"_
or MStringAt(source, current - 2, 6, "BACHER", "MACHER")) ) then
out1 = out1 + "K"
out2 = out2 + "K"
current = current + 2
elseif current = 1 AND MStringAt(source, current, 6, "CAESAR") then
// special case 'caesar' (why didn't this go at the top?)
out1 = out1 + "S"
out2 = out2 + "S"
current = current + 2
elseif MStringAt(source, current, 4, "CHIA") then
// italian 'chianti'
out1 = out1 + "K"
out2 = out2 + "K"
current = current + 2
elseif MStringAt(source, current, 2, "CH") then
// find 'michael'
if current > 0 AND MStringAt(source, current, 4, "CHAE") then
out1 = out1 + "K"
out2 = out2 + "X"
current = current + 2
break
elseif current = 0 _
and (MStringAt(source, current + 1, 5, "HARAC", "HARIS") _
or MStringAt(source, current + 1, 3, "HOR", "HYM", "HIA", "HEM")) _
and not MStringAt(source, 0, 5, "CHORE") then
// greek roots e.g. 'chemistry', 'chorus'
out1 = out1 + "K"
out2 = out2 + "K"
current = current + 2
else
//germanic, greek, or otherwise 'ch' for 'kh' sound
if((MStringAt(source, 0, 4, "VAN ", "VON ") or MStringAt(source, 0, 3, "SCH")) _
_ // 'architect but not 'arch', 'orchestra', 'orchid'
or MStringAt(source, current - 2, 6, "ORCHES", "ARCHIT", "ORCHID") _
or MStringAt(source, current + 2, 1, "T", "S") _
or ((MStringAt(source, current - 1, 1, "A", "O", "U", "E") OR current = 1) _
_ //e.g., 'wachtler', 'wechsler', but not 'tichner'
and MStringAt(source, current + 2, 1, "L", "R", "N", "M", "B", "H", "F", "V", "W", " "))) then
out1 = out1 + "K"
out2 = out2 + "K"
else
if current > 1 then
if MStringAt(source, 1, 2, "MC") then
//e.g., "McHugh"
out1 = out1 + "K"
out2 = out2 + "K"
else
out1 = out1 + "X"
out2 = out2 + "K"
end if
else
out1 = out1 + "X"
out2 = out2 + "X"
end if
end if
current = current + 2
end if
// end of CH case
elseif MStringAt(source, current, 2, "CZ") and not MStringAt(source, current - 2, 4, "WICZ") then
//e.g, 'czerny'
out1 = out1 + "S"
out2 = out2 + "X"
current = current + 2
elseif MStringAt(source, current + 1, 3, "CIA") then
//e.g., 'focaccia'
out1 = out1 + "X"
out2 = out2 + "X"
current = current + 3
elseif MStringAt(source, current, 2, "CC") and not (current = 2 AND charAt(1) = "M") then
// double "C", but not if e.g. 'McClellan'
//'bellocchio' but not 'bacchus'
if MStringAt(source, current + 2, 1, "I", "E", "H") and not MStringAt(source, current + 2, 2, "HU") then
//'accident', 'accede" "succeed'
if((current = 2 AND charAt(current - 1) = "A") _
OR MStringAt(source, current - 1, 5, "UCCEE", "UCCES")) then
out1 = out1 + "KS"
out2 = out2 + "KS"
//'bacci', 'bertucci', other italian
else
out1 = out1 + "X"
out2 = out2 + "X"
end if
current = current + 3
else // Pierce's rule
out1 = out1 + "K"
out2 = out2 + "K"
current = current + 2
end if
elseif MStringAt(source, current, 2, "CK", "CG", "CQ") then
out1 = out1 + "K"
out2 = out2 + "K"
current = current + 2
elseif MStringAt(source, current, 2, "CI", "CE", "CY") then
// italian vs. english
if MStringAt(source, current, 3, "CIO", "CIE", "CIA") then
out1 = out1 + "S"
out2 = out2 + "X"
else
out1 = out1 + "S"
out2 = out2 + "S"
end if
current = current + 2
else
// all other C cases are considered a K:
out1 = out1 + "K"
out2 = out2 + "K"
// name sent in 'mac caffrey', 'mac gregor'
if MStringAt(source, current + 1, 2, " C", " Q", " G" ) then
current = current + 3
else