-
Notifications
You must be signed in to change notification settings - Fork 2
/
MyStrUtils.pas
2291 lines (1918 loc) · 74.9 KB
/
MyStrUtils.pas
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
{*
MyStrUtils.pas - functions to make string handling easier and more convenient.
---------------
Begin: 2005/01/06
Last revision: $Date: 2011-03-30 19:08:03 $ $Author: areeves $
Version number: $Revision: 1.91 $
Code Documentation Tags: Begin 2009-08-14, Last Revision: 2009-08-18
Project: APHI General Purpose Delphi Library
Website: http://www.naadsm.org/opensource/delphi
Author: Aaron Reeves <Aaron.Reeves@colostate.edu>
--------------------------------------------------
Copyright (C) 2005 - 2013 NAADSM Development Team
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
}
(*
Documentation generation tags begin with {* or ///
Replacing these with (* or // foils the documentation generator
Some of these functions may be automatically tested. If the symbol
TESTING is defined in Defs.inc, the appropriate test code is automatically
run when this unit is initialized. Please see the test code and the
initialization section at the end of this unit.
Short function descriptions are provided in the interface section. More
detailed comments are provided in the implementation section as needed.
*)
unit MyStrUtils;
interface
uses
SysUtils,
Variants,
TypInfo
;
// Unit self-test
//--------------------
procedure selfTest();
// Special characters
//-------------------
const
endl: string = #13#10; /// Endline: Carriage Return + Line Feed
CHAR_BACKSPACE: char = #8; /// Backspace character
CHAR_TAB: char = #9; /// Tab character
tab: char = #9; /// Tab character
CHAR_NULL: char = #0; /// Null character
CHAR_LEFT_ARROW: char = #37; /// Left Arrow character
CHAR_UP_ARROW: char = #38; /// Up Arrow character
CHAR_RIGHT_ARROW: char = #39; /// Right Arrow character
CHAR_DOWN_ARROW: char = #40; /// Down Arrow character
// Substrings
//-----------
{ Returns the character at the zero-indexed position in the string }
function charAt( const str: string; pos: integer ): char;
{ Is the string empty? }
function strIsEmpty( const str: string ): boolean;
// Changing case
//---------------
{ Converts string to all lower case }
function lower( const str: string ): string;
{ Converts string to all upper case }
function upper( const str: string ): string;
{ Converts the first character of the string to upper case }
function capitalize( const str: string ): string;
// Int conversions
//----------------
function myStrToInt( const str: string; default: integer = 0; raiseException: boolean = false ): integer;
// Float conversions
//------------------
{ Converts string to float using local regional settings. }
function uiStrToFloat( const str: string; default: double = 0.0; raiseException: boolean = false ): double;
{ Converts floats to strings using local regional settings. Useful for user interface display. }
function uiFloatToStr( const val: double; const rndToPlace: integer = 6; const trunc: boolean = true ): string;
{ Same as uiFloatToStr, but 0's are added to the end of the string if necessary to get to the specified number of places. Useful for currency. }
function uiFloatToStrZeroPadded( const val: double; const rndToPlace: integer; const trunc: boolean = true ): string;
{ Converts string to float using US regional settings. }
function usStrToFloat( const str: string; default: double = 0.0; raiseException: boolean = false ): double;
{ Converts floats to strings using US English regional settings. Useful for writing XML, SQL. }
function usFloatToStr( const val: double; const rndToPlace: integer = 6; const trunc: boolean = true ): string;
{ Same as usFloatToStr, but 0's are added to the end of the string if necessary to get to the specified number of places. Useful for currency. }
function usFloatToStrZeroPadded( const val: double; const rndToPlace: integer; const trunc: boolean = true ): string;
{ Use application-specific delimiters, if available. Otherwise, uses local regional settings. }
function csvStrToFloat( str: string; default: double = 0.0; raiseException: boolean = false ): double;
function csvFloatToStr( const val: double ): string;
{ Converts floats to strings for debugging messages. Currently an alias for usFloatToStr, but this could be changed. }
function dbFloatToStr( const val: double ): string;
// Bool conversions
//-----------------
{ Writes translated versions of "true" or "false" }
function uiBoolToText( const val: boolean ): string;
{ Writes the strings "true" or "false". Useful for XML, SQL. Contrast to SysUtils.boolToStr(), which returns "-1" or "0", respectively. }
function usBoolToText( const val: boolean ): string;
function usTextToBool( val: string ): boolean;
function boolToInt( const val: boolean ): integer; // FIX ME: may be unnecessary.
function intToBool( const val: integer ): boolean; // FIX ME: may be unnecessary.
// String formatting
//------------------
{ Appends bitToAppend to the existing string val. }
procedure appendToString( var val: string; bitToAppend: string );
{ Strips leading and trailing whitespace, converts to lower case. }
function fixUp( const val: string ): string;
{ Breaks a long string into multiple lines }
function prettyPrint(
const srcStr: string;
prefLineLen: integer = 50;
usePunct: boolean = true;
forceBreak: boolean = true
): string;
{ Helper Method used by prettyPrint() }
function splitNear(
pos: integer;
var str: string;
maxLenAdd: integer = 0;
usePunct: boolean = true;
forceBreak: boolean = true
): string;
// Determining character type
//----------------------------
{ Is the character white space? See detailed comment. }
function isSpace( const ch: char ): boolean;
{ Is the character a special symbol? See comments in function. }
function isPunct( const ch: char ): boolean;
{ Is the comment a number? }
function isDigit( const ch: char ): boolean;
// Functions for filename handling
//--------------------------------
type TPathName = type string; /// a string for filename operations; in cases holding the filename, not the path
{ Returns the file name without other path elements }
function shortFileName( const path: TPathName ): TPathName;
{ returns the file name without its extension }
function stripExtension( const path: TPathName ): TPathName;
{ Returns just the directory path associated with a file, with a trailing backslash. }
function directory( const path: TPathName ): TPathName;
{ For a directory (with a trailing slash), returns the name of the parent directory.
For a file, this is the same as directory(). }
function parentDirectory( const path: TPathName ): TPathName;
{ Returns the directory path of the current executable, with a trailing backslash. }
function appPath(): TPathName;
{ Abbreviates the pathname by excising pieces from the middle of the string. See detailed comment. }
function abbrevPath( path: TPathName; Count: Integer = 40 ): string;
{ Is the specified path absolute or relative? NOTE: this has nothing to do with whether the directory exists or is accessible. }
function isAbsolutePath( path: TPathName ): boolean;
// Number formatting
//------------------
function firstNonZeroChar( const str: string; const fromEnd: boolean = false ): integer;
function isNonZeroNumChar( const ch: char ): boolean;
function paddedInt( toPad: integer; places: integer; padChar: string = '0' ): string;
// Delimited lists
//----------------
{ Returns items from a delimited list in a one-line string }
function getElementStr( n: word; Delimiter: Char; ln: string ): string;
// FIX ME: this function is 1-indexed!!!
//function GetElement( n: word; Delimiter: Char; ln: string ): variant;
// XML/HTML encoding/decoding
//----------------------------
function encodeXml( const s: string; const allowQuotesAndCommas: boolean = false ): string;
function decodeXml( const s: string ): string;
function encodeHtml( const s: string ): string;
function decodeHtml( const s: string ): string;
function stripXmlHeaders( const s: string ): string;
// CSV formatting
//---------------
function csvQuote( const s: string ): string;
// RC4 encryption/decryption
//--------------------------
{ Note: this function requires genprps.dll }
function rc4Encrypt( const str, password: string ): string;
// Hex encoding/decoding
//----------------------
{ Note: these functions require genprps.dll }
function hexEncode( str: string ): string;
function hexDecode( str: string ): string;
// Working with string and character pointers
//-------------------------------------------
procedure appendToPstring( pstr: pstring; str: string );
procedure prependToPstring( pstr: pstring; str: string );
// Testing functions
//------------------
//procedure zzTestsubstrReplace();
procedure zzTestFirstNonZeroChar();
procedure zzTestFileNameUtils();
implementation
uses
Windows, // includes functions for DLL loading
Forms, // includes Application object
Dialogs,
Math,
StrUtils,
RegExpr,
DebugWindow,
CStringList,
RoundToXReplacement_3c,
FunctionPointers,
I88n
;
var
/// Variables for loading the DLL genprps.dll
//------------------------------
dllLoadErrors: string; /// Holds messages regarding errors loading genprps.dll
atrConfLoaded: boolean; /// For loading the DLL genprps.dll
_rc4Encrypt: TCFnPChar_2_Charp_Charp; /// For loading the DLL genprps.dll
_hexEncode: TCFnPChar_1_Charp; /// For loading the DLL genprps.dll
_hexDecode: TCFnPChar_1_Charp; /// For loading the DLL genprps.dll
_usFormatSettings: TFormatSettings; /// For float conversion and other formatting
const
DBSHOWMSG: boolean = true; /// set to true to enable debugging messages for this unit.
NAN_STRING = '(Not a number)'; /// holds 'Not a number'
INF_STRING = '(Negative infinity)'; /// holds 'Negative infinity'
NEG_INF_STRING = '(Infinity)'; /// holds 'Infinity
//-----------------------------------------------------------------------------
// Delimited lists
//-----------------------------------------------------------------------------
{*
Returns a string (as variant) from a delimited string at delimiter position n
@param n Which element in the delimited string to return
@param Delimiter Character that delimits elements of text within the string
@param ln Delimited string
@return Contents of element n of string ln or null if element n does not exist
}
function GetElement( n: word; Delimiter: Char; ln: string ): variant;
var
p, cnt: longint;
element: string;
begin
ln := ln + Delimiter; // add delimiter to get the last one
cnt := 0;
repeat
p := Pos( Delimiter,ln );
if( p > 0 ) then
begin
element := Copy( ln, 1, p - 1);
Delete(ln, 1, p);
cnt := cnt + 1;
end
;
until (p = 0) or (cnt = n);
if (p = 0) and (cnt < n) then
Result := null
else
Result := element
;
end
;
{*
Returns a string from a delimited string at delimiter position n
@param n Which element in the delimited string to return
@param Delimiter Character that delimits elements of text within the string
@param ln Delimited string
@return Contents of element n of string ln or empty string if element n does not exist
}
function getElementStr( n: word; Delimiter: Char; ln: string ): string;
var
v: variant;
begin
// Remember: the screwy getElement function is 1-indexed.
// FIX ME: that should be changed!!
v := getElement( n + 1, delimiter, ln );
if( null = v ) then
result := ''
else
result := string( v )
;
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Int conversions
//-----------------------------------------------------------------------------
{*
Converts the contents of str to an integer
@param str A string holding numeric characters
@param default Default integer value to return if the conversion fails
@param raiseException Whether to raise an exception if the conversion fails
@throws Optionally, an exception can be raised indicating str can not be converted
@return Integer if sucess or default if the conversion fails
}
function myStrToInt( const str: string; default: integer = 0; raiseException: boolean = false ): integer;
var
d: integer;
str2: string;
begin
str2 := fixup( str );
if( tryStrToInt( str2, d ) ) then
result := d
else
begin
if( raiseException ) then
raise exception.Create( 'Cannot convert "' + str + '" to an integer.' )
;
result := default;
end
;
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Float conversions
//-----------------------------------------------------------------------------
{*
Converts the contents of str to a double
@param str A string holding numeric characters
@param default Default double value to return if the conversion fails
@param raiseException Whether to raise an exception if the conversion fails
@throws Optionally, an exception can be raised indicating str can not be converted
@return Double if success or default if the conversion fails
}
function uiStrToFloat( const str: string; default: double = 0.0; raiseException: boolean = false ): double;
var
d: double;
str2: string;
begin
str2 := fixup( str );
if( 0 = length( str2 ) ) then
result := default
else if( tryStrToFloat( str2, d ) ) then
result := d
else
begin
if( raiseException ) then
raise exception.Create( 'Cannot convert "' + str + '" to a double.' )
;
result := default;
end
;
end
;
{*
Converts the contents of str to a double using English localization format
@param str A string holding numeric characters
@param default Default double value to return if the conversion fails
@param raiseException Whether to raise an exception if the conversion fails
@throws Optionally, an exception can be raised indicating str can not be converted
@return Double if success or default if the conversion fails
}
function usStrToFloat( const str: string; default: double = 0.0; raiseException: boolean = false ): double;
var
d: double;
str2: string;
begin
str2 := fixup( str );
if( tryStrToFloat( str2, d, _usFormatSettings ) ) then
result := d
else
begin
if( raiseException ) then
raise exception.Create( 'Cannot convert "' + str + '" to a double.' )
;
result := default;
end
;
end
;
{*
Converts the contents of str to a double replacing the the I88n decimal place separator
stored in _Settings with the character used by the System
@param str A string holding numeric characters
@param default Default double value to return if the conversion fails
@param raiseException Whether to raise an exception if the conversion fails
@return Double if success or default if the conversion fails
@comment Fix Me: Is this Desc correct - check with Aaron
}
function csvStrToFloat( str: string; default: double = 0.0; raiseException: boolean = false ): double;
begin
str := ansiReplaceStr( str, csvDecPt, SysUtils.DecimalSeparator );
result := usStrToFloat( str );
end
;
{*
Converts the contents of val to a string rounded to rndToPlace digits
using English decimal point formating
@param val Numeric floating point value to be converted to string
@param rndToPlace Number of desired significant didgits
@param trunc Whether to truncate
@return String representation of formatted Double
or NAN_STRING if val is not valid numeric
or INF_STRING or NEG_INF_STRING if val is an infinite number
@comment Fix Me: This needs more detail, for example what exatly does truncate do - check with Aaron
}
function usFloatToStr( const val: double; const rndToPlace: integer = 6; const trunc: boolean = true ): string;
begin
if( isNaN( val ) ) then
begin
result := NAN_STRING;
exit;
end
;
if( IsInfinite( val ) ) then
begin
if( math.NegativeValue = sign( val ) ) then
result := INF_STRING
else
result := NEG_INF_STRING
;
exit;
end
;
try
if( trunc ) then
begin
if( power( 10, -1 * rndToPlace ) > abs( val ) ) then
result := floatToStr( 0.0, _usFormatSettings )
else
result := floatToStr( RoundDblTo( val, -1 * rndToPlace, drHalfUp ), _usFormatSettings )
;
end
else
result := format( '%.' + intToStr( rndToPlace ) + 'f', [val] )
;
except
result := '(Error during floatToStr conversion)';
end;
end
;
{*
Converts the contents of val to a string rounded to rndToPlace digits
using System localization decimal point formating
@param val Numeric floating point value to be converted to string
@param rndToPlace Number of desired significant didgits
@param trunc Whether to truncate
@return String representation of formatted Double
or NAN_STRING if val is not valid numeric
or INF_STRING or NEG_INF_STRING if val is an infinite number
@comment Fix Me: This needs more detail, for example what exatly does truncate do - check with Aaron
}
function uiFloatToStr( const val: double; const rndToPlace: integer = 6; const trunc: boolean = true ): string;
begin
result := usFloatToStr( val, rndToPlace, trunc );
if( ( NAN_STRING = result ) or ( INF_STRING = result ) or ( NEG_INF_STRING = result ) ) then
result := tr( result )
else if( '.' <> SysUtils.DecimalSeparator ) then
result := ansiReplaceStr( result, '.', SysUtils.DecimalSeparator )
;
end
;
{*
Converts val to a string, English formated decimal character
@param val Numeric floating point value
@return Numeric formatted as string using English notation
}
function csvFloatToStr( const val: double ): string;
begin
result := usFloatToStr( val );
if( '.' <> csvDecPt ) then
result := ansiReplaceStr( result, '.', csvDecPt )
;
end
;
{*
Converts the contents of val to a string rounded to rndToPlace digits
using English decimal point formating and padding with 0's if necessary
@param val Numeric floating point value to be converted to string
@param rndToPlace Number of desired significant didgits
@param trunc Whether to truncate
@return String representation of formatted Double
or NAN_STRING if val is not valid numeric
or INF_STRING or NEG_INF_STRING if val is an infinite number
@comment Fix Me: This needs more detail, for example what exatly does truncate do - check with Aaron
}
function usFloatToStrZeroPadded( const val: double; const rndToPlace: integer; const trunc: boolean = true ): string;
var
decimalPart: string;
i: integer;
begin
result := usFloatToStr( val, rndToPlace, trunc );
if( ( NAN_STRING = result ) or ( INF_STRING = result ) or ( NEG_INF_STRING = result ) ) then
// do nothing
else
begin
// Fill trailing 0's out to the desired number of decimal places, if necessary.
if( 0 = pos( '.', result ) ) then
result := result + '.'
;
decimalPart := rightStr( result, length( result ) - pos( '.', result ) );
for i := length( decimalPart ) to rndToPlace - 1 do
result := result + '0'
;
end
;
end
;
{*
Converts the contents of val to a string rounded to rndToPlace digits
using System decimal point formating and padding with 0's if necessary
@param val Numeric floating point value to be converted to string
@param rndToPlace Number of desired significant didgits
@param trunc Whether to truncate
@return String representation of formatted Double
or NAN_STRING if val is not valid numeric
or INF_STRING or NEG_INF_STRING if val is an infinite number
@comment Fix Me: This needs more detail, for example what exatly does truncate do - check with Aaron
}
function uiFloatToStrZeroPadded( const val: double; const rndToPlace: integer; const trunc: boolean = true ): string;
begin
result := usFloatToStrZeroPadded( val, rndToPlace, trunc );
if( ( NAN_STRING = result ) or ( INF_STRING = result ) or ( NEG_INF_STRING = result ) ) then
result := tr( result )
else if( '.' <> SysUtils.DecimalSeparator ) then
result := ansiReplaceStr( result, '.', SysUtils.DecimalSeparator )
;
end
;
{*
Converts the contents of val to a string rounded to 6 digits
using English decimal point formating
@param val Numeric floating point value to be converted to string
@return String representation of formatted Double
or NAN_STRING if val is not valid numeric
or INF_STRING or NEG_INF_STRING if val is an infinite number
}
function dbFloatToStr( const val: double ): string;
begin
result := usFloatToStr( val );
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Bool conversions
//-----------------------------------------------------------------------------
{*
Evaluates val and returns True or False
@param val An integer value
@return Returns False if val is 0 else True
}
function intToBool( const val: integer ): boolean;
begin
if( val = 0 ) then
result := false
else
result := true
;
end
;
{*
Evaluates val and returns 0 or -1
@param val A boolean, True or False
@return Returns -1 if val is True else 0
}
function boolToInt( const val: boolean ): integer;
begin
if( val = true ) then
result := -1
else
result := 0
;
end
;
{*
Evaluates val and returns translated text for 'true' or 'false'
@param val A boolean, True or False
@return Returns translated text for 'true' if val is True else 'false'
}
function uiBoolToText( const val: boolean ): string;
begin
if( val ) then
result := tr( 'true' )
else
result := tr( 'false' )
;
end
;
{*
Evaluates val and returns text 'true' or 'false'
@param val A boolean, True or False
@return Returns 'true' if val is True else 'false'
@comment Contrast to SysUtils.boolToStr(), which returns "-1" or "0", respectively.
}
function usBoolToText( const val: boolean ): string;
begin
if( val ) then
result := 'true'
else
result := 'false'
;
end
;
{*
Converts a string (e.g., "true" or "F") to a boolean.
@param val The string to convert
@return True or False
@comment An exception is raised if "val" is not a recognized string.
}
function usTextToBool( val: string ): boolean;
begin
val := fixup( val );
if
( 'true' = val )
or
( 't' = val )
or
( '1' = val )
or
( '-1' = val )
or
( 'yes' = val )
or
( 'y' = val )
then
result := true
else if
( 'false' = val )
or
( 'f' = val )
or
( '0' = val )
or
( 'no' = val )
or
( 'n' = val )
then
result := false
else
begin
raise exception.Create( 'Unrecognized value "' + val + '" in usTextToBool()' );
result := false;
end
;
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Filename handling
//-----------------------------------------------------------------------------
{*
Returns the filename without any other path information.
For example, shortFileName( 'c:\foo\bar.txt' ) is 'bar.txt'.
Also, shortFileName( 'c:/foo/bar.txt' ) is 'bar.txt'.
This function is tested by zzTestFileNameUtils().
@param path Full file name (path and file name)
@return A string containing the file name
@comment It is tempting to use the Delphi function extractFileName() directly.
Unfortunately, extractFileName() does not properly handle forward slashes.
}
function shortFileName( const path: TPathName ): TPathName;
var
str2: string;
begin
// Replace forward slashes with back slashes
str2 := path;
//substrReplace( str2, '/', '\', true );
str2 := StringReplace( str2, '/', '\', [rfReplaceAll] );
result := extractFileName( str2 );
end
;
{*
Returns a pathname without the filename extension. For example,
stripExtension( 'c:\foo\bar.txt' ) is 'c:\foo\bar'.
This function is tested by zzTestFileNameUtils().
@param path Full file name (path and file name)
@return A string containing the file name w/o ext.
}
function stripExtension( const path: TPathName ): TPathName;
var
xs: integer;
xstr, xstr1: string;
begin
xs := 0;
xstr1 := '';
while( ( xstr1 <> '.' ) and ( xs <> length( path ) ) ) do
begin
xs := xs + 1;
xstr := rightStr( path, xs );
xstr1 := leftStr( xstr, 1 );
end
;
if( xs < length( path ) ) then
result := leftStr( path, length( path ) - xs )
else
result := path
;
end
;
{*
Returns just the directory path associated with a file. For
example, directory( '/home/foo/bar.txt' ) is '/home/foo/'.
Note that the trailing slash is included.
It is tempting to use the Delphi function extractFileDir() directly,
but extractFileDir() does not properly handle forward slashes.
This function is tested by zzTestFileNameUtils().
@param path Full file name (path and file name)
@return A string containing the directory path, but not the filename
@comment Any forward slashes are replaced with back slashes
and the directory name will be followed by a '\'
}
function directory( const path: TPathName ): TPathName;
var
str2: string;
begin
// Replace forward slashes with back slashes
str2 := trim( path );
str2 := StringReplace( str2, '/', '\', [rfReplaceAll] );
result := extractFileDir( str2 );
if( rightStr( result, 1 ) <> '\' ) then
result := result + '\'
;
end
;
{*
For a directory (with a trailing slash), returns the name of the parent directory.
For a file, this is the same as directory().
For example, C:\foo\bar.ex returns C:\foo\
@param path Full file name (path and file name)
@return A string containing the directory path, but not the filename
@comment Any forward slashes are replaced with back slashes
and the directory name will be followed by a '\'
}
function parentDirectory( const path: TPathName ): TPathName;
var
temp: string;
begin
temp := trim( path );
if( ( '\' = rightStr( temp, 1 ) ) or ( '/' = rightStr( temp, 1 ) ) ) then
temp := leftStr( temp, length( temp ) - 1 )
;
result := directory( temp );
end
;
{*
Returns the directory path of the current executable.
Note that the trailing slash is included.
@return Directory path of the current executable
}
function appPath(): TPathName;
begin
result := directory( Application.ExeName );
end
;
{*
Path is a long path to the file (for example, 'c:\Program Files\AAA\BBB\CCC\DDD\fff.txt').
abbrevPath function returns a short path (for example, 'c:\Program Files\...\DDD\fff.txt')
and Count parameter is a limit of this short path. Length of short path will be less
than "Count" symbols.
This function is adapted from the following web site:
http://www.greatis.com/delphicb/tips/lib/filesdirectories-getshortpath.html
@param path Full file name (path and file name)
@param Count Limits how many subdirectories to remove from path
@return A string containing and abbreviated path to the file
@comment The method operates on backslashes, forward slashes are ignored
}
function abbrevPath( path: TPathName; Count: Integer = 40 ): string;
// Inline helper to delete chunks of the string before consecutive '\'
procedure Slashes(var Str: string; var Num: Integer);
var
Position, Index: Integer;
begin
Index:=0;
repeat
Position:=Pos('\', Str);
Delete(Str,1,Position);
if Position<>0 then Inc(Index);
if (Index=Num)and(Num<>0) then break;
until Position=0;
Num:=Index;
end
;
var
Num, NewNum, P: Integer;
Str: string;
begin
Str:=Path;
Num:=0;
Slashes( string(Path), Num);
while (Length(Str)>Count)and(Num>2) do
begin
NewNum:=Num div 2;
Path:=Str;
Slashes( string(Path), NewNum);
P:=Pos(Path, Str);
Delete(Str,P, Length(Path));
NewNum:=2;
Slashes( string(Path), NewNum);
Str:=Str+'...\'+Path;
Dec(Num);
end;
Result:=Str;
end
;
{*
Validates whether path is an absolute path using the UNC convention
@param path Full file name (path and file name)
@return True if UNC convention followed, else false
}
function isAbsolutePath( path: TPathName ): boolean;
begin
path := trim( path );
// See if the path is an absolute path using the UNC convention
if( ( '\\' = leftStr( path, 2 ) ) or ( '//' = leftStr( path, 2 ) ) ) then
result := true
// See if the path matches a regular expression for a drive letter
else if ExecRegExpr( '^[A-Za-z]:[\\/][A-Za-z1-9_.-]$', leftStr( path, 4 ) ) then
result := true
// Otherwise, it's not an absolute path
else
result := false
;
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// String formatting
//-----------------------------------------------------------------------------
{*
Strips leading and trailing whitespace
}
(*
function RemoveWhites ( const str: WideString ): WideString;
var
i: integer;
begin
for i := 1 to Length (str) do
if Ord(str[i]) >= 32 then
Result := Result + str [i];
Result := Trim (Result);
end
;
*)
{*
Appends bitToAppend to existing string val. Note that val is passed by reference: its value will be updated.
@param val The existing string to which the new bit will be appended
@param bitToAppend The string to append to the existing string
}
procedure appendToString( var val: string; bitToAppend: string );
begin