forked from pharo-project/pharo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString.class.st
More file actions
3016 lines (2495 loc) · 96.4 KB
/
Copy pathString.class.st
File metadata and controls
3016 lines (2495 loc) · 96.4 KB
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
"
A String is an indexed collection of Characters. Class String provides the abstract super class for ByteString (that represents an array of 8-bit Characters) and WideString (that represents an array of 32-bit characters). In the similar manner of LargeInteger and SmallInteger, those subclasses are chosen accordingly for a string; namely as long as the system can figure out so, the String is used to represent the given string.
Strings support a vast array of useful methods, which can best be learned by browsing and trying out examples as you find them in the code.
## Substrings and slicing
A number of selectors can be used to get substrings. `String>>#lines` will return a colection containing substrings separated by `\\n`, `\\r`, or `\\r\\n`; `String>>#trim` will return a substring with whitespace removed from the beginning and end.
Obtaining parts of a string can also be achieved using numbered indices, also known as slicing. There are shortcut methods for some common operations that are often inherited from `SequenceableCollection` inclusing `allButFirst`, `allButLast`, `first`, or `last`.
```
s := 'abcdefg'.
s first. ""$a""
s allButFirst. ""bcdefg""
s last. ""$g""
s allButLast. ""abcdef""
""pass a number argument to change the number of characters removed/kept""
s first: 2. ""ab""
s allButFirst: 2. ""cdefg""
s last: 2. ""fg""
s allButLast: 2. ""abcde""
```
To get the middle of a string use `SequenceableCollection>>#copyFrom:to:`
```
s := 'abcdefg'.
s copyFrom: 2 to: 6. ""bcdef""
```
To count back from the end of the string use the `size` selector
```
s := 'abcdefg'
s copyFrom: 2 to: s size - 1
```
## Formatting
Strings have a `String>>#format:` selector that can be used for interpolating other objects.
The ""string template"" can either have numbers between curly bracket characters (`{` and `}`)
where the argument to format is a collection where values are indexed by number. Or pass in
a `HashedCollection` where the placeholders are the keys of the collection
```
'ab {1} ef {2}' format: {'cd'. 'gh'}. ""ab cd ef gh""
'ab {one} ef {two}' format:
(Dictionary with: #one -> 'cd' with: #two -> 'gh').
```
`String>>#contractTo:` is also useful for shortening strings to a particular length by replacing
middle characters.
## Copying and Streaming
As well as the `format:` selector it is possible to build up a string using contatenation with
`SequenceableCollection>>#,`
```
a := 'abc'.
b := ' easy as '.
c := '123'.
a , b , c. ""abc easy as 123""
```
Or alternatively, construct a string from a stream using `SequenceableCollection class>>#streamContents:`.
```
s := String streamContents: [ :stream |
stream nextPutAll: 'abcdefg';
space;
nextPutAll: '123456';
space.
'7890' putOn: stream. ]. ""abcdefg 123456 7890""
```
## Finding/Searching
Simple reqular expression type searching can be performed using `String>>#match:`, which has similar
symantics as ""globbing"" in a shell. The reciever is a template string where the `#` character matches any single character and the `*` character matches any number of characters. A `Boolean` object is returned.
```
'#abb*cdch' match: '4abbadskfakjdfadiadfnvcdch' ""true""
```
For more complex matching use `String>>#matchesRegex:` which is an extension method implmented by `RxMatcher`. See the help documentation on regular expressions `HelpBrowser openOn: RegexHelp.`
"
Class {
#name : 'String',
#superclass : 'ArrayedCollection',
#classVars : [
'AsciiOrder',
'CSLineEnders',
'CSNonSeparators',
'CSSeparators',
'CaseInsensitiveOrder',
'CaseSensitiveOrder',
'LowercasingTable',
'Tokenish',
'TypeTable',
'UppercasingTable'
],
#category : 'Collections-Strings-Base',
#package : 'Collections-Strings',
#tag : 'Base'
}
{ #category : 'primitives' }
String class >> compare: string1 with: string2 collated: order [
"Return -1, 0 or 3, if string1 is <, =, or > string2, with the collating order of characters given by the order array."
| len1 len2 c1 c2 |
order ifNil: [
len1 := string1 size.
len2 := string2 size.
1 to: (len1 min: len2) do: [ :i |
c1 := string1 basicAt: i.
c2 := string2 basicAt: i.
c1 = c2 ifFalse: [
^ c1 < c2
ifTrue: [ -1 ]
ifFalse: [ 1 ] ] ].
len1 = len2 ifTrue: [ ^ 0 ].
^ len1 < len2
ifTrue: [ -1 ]
ifFalse: [ 1 ] ].
len1 := string1 size.
len2 := string2 size.
1 to: (len1 min: len2) do: [ :i |
c1 := string1 basicAt: i.
c2 := string2 basicAt: i.
c1 < 256 ifTrue: [ c1 := order at: c1 + 1 ].
c2 < 256 ifTrue: [ c2 := order at: c2 + 1 ].
c1 = c2 ifFalse: [
^ c1 < c2
ifTrue: [ -1 ]
ifFalse: [ 1 ] ] ].
len1 = len2 ifTrue: [ ^ 0 ].
^ len1 < len2
ifTrue: [ -1 ]
ifFalse: [ 1 ]
]
{ #category : 'instance creation' }
String class >> cr [
"Answer a string containing a single carriage return character."
^ self with: Character cr
]
{ #category : 'instance creation' }
String class >> crlf [
"Answer a string containing a carriage return and a linefeed."
^ self with: Character cr with: Character lf
]
{ #category : 'instance creation' }
String class >> empty [
"A canonicalized empty String instance."
^ ''
]
{ #category : 'formatting' }
String class >> expandMacro: macroType argument: argument withExpansions: expansions [
macroType = $s ifTrue: [^expansions at: argument].
macroType = $p ifTrue: [^(expansions at: argument) printString].
macroType = $n ifTrue: [^String cr].
macroType = $t ifTrue: [^String tab].
self error: 'unknown expansion type'
]
{ #category : 'primitives' }
String class >> findFirstInString: aString inCharacterSet: aCharacterSet startingAt: start [
"Trivial, non-primitive version"
start
to: aString size
do: [:i | (aCharacterSet
includes: (aString at: i))
ifTrue: [^ i]].
^ 0
]
{ #category : 'primitives' }
String class >> findFirstInString: aString inSet: inclusionMap startingAt: start [
"Trivial, non-primitive version"
| i stringSize ascii more |
inclusionMap size ~= 256 ifTrue: [^ 0].
stringSize := aString size.
more := true.
i := start - 1.
[more and: [(i := i + 1) <= stringSize]] whileTrue: [
ascii := (aString basicAt: i).
more := ascii < 256 ifTrue: [(inclusionMap at: ascii + 1) = 0] ifFalse: [true].
].
i > stringSize ifTrue: [^ 0].
^ i
]
{ #category : 'instance creation' }
String class >> fromByteArray: aByteArray [
^ aByteArray asString
]
{ #category : 'instance creation' }
String class >> fromString: aString [
"Answer an instance of me that is a copy of the argument, aString."
^ aString copyFrom: 1 to: aString size
]
{ #category : 'primitives' }
String class >> indexOfAscii: anInteger inString: aString startingAt: start [
start to: aString size do: [ :index |
(aString basicAt: index) = anInteger ifTrue: [ ^index ] ].
^0
]
{ #category : 'class initialization' }
String class >> initialize [
self initializeTypeTable.
AsciiOrder := self newAsciiOrder.
CaseInsensitiveOrder := self newCaseInsensitiveOrder.
CaseSensitiveOrder := self newCaseSensitiveOrder.
LowercasingTable := self newLowercasingTable.
UppercasingTable := self newUppercasingTable.
Tokenish := self newTokenish.
CSLineEnders := self newCSLineEnders.
"separators and non-separators"
CSSeparators := CharacterSet separators.
CSNonSeparators := CSSeparators complement
]
{ #category : 'private - initialization' }
String class >> initializeTypeTable [
| newTable |
newTable := Array new: 256 withAll: #xBinary. "default"
newTable atAll: #(9 10 12 13 32 ) put: #xDelimiter. "tab lf ff cr space"
newTable atAll: ($0 asciiValue to: $9 asciiValue) put: #xDigit.
1 to: 255
do: [:index |
(Character value: index) isLetter
ifTrue: [newTable at: index put: #xLetter]].
newTable at: 30 put: #doIt.
newTable at: $" asciiValue put: #xDoubleQuote.
newTable at: $# asciiValue put: #xLitQuote.
newTable at: $$ asciiValue put: #xDollar.
newTable at: $' asciiValue put: #xSingleQuote.
newTable at: $: asciiValue put: #xColon.
newTable at: $( asciiValue put: #leftParenthesis.
newTable at: $) asciiValue put: #rightParenthesis.
newTable at: $. asciiValue put: #period.
newTable at: $; asciiValue put: #semicolon.
newTable at: $[ asciiValue put: #leftBracket.
newTable at: $] asciiValue put: #rightBracket.
newTable at: ${ asciiValue put: #leftBrace.
newTable at: $} asciiValue put: #rightBrace.
newTable at: $^ asciiValue put: #upArrow.
newTable at: $_ asciiValue put: #xLetter. "by default, do not accept _ as assignement"
newTable at: $| asciiValue put: #verticalBar.
TypeTable := newTable
]
{ #category : 'instance creation' }
String class >> lf [
"Answer a string containing a single carriage return character."
^ self with: Character lf
]
{ #category : 'instance creation' }
String class >> loremIpsum [
"Return a constant string with one paragraph of text, the famous Lorem ipsum filler text.
The result is pure ASCII (Latin words) and contains no newlines."
^ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
]
{ #category : 'instance creation' }
String class >> loremIpsum: size [
"Return a mostly random multi-paragraph filler string of the specified size.
The result is pure ASCII, uses CR for newlines and ends with a dot and newline."
"self loremIpsum: 2048"
| words out |
words := (self loremIpsum findTokens: ' ,.') collect: [:each | each asLowercase].
(out := LimitedWriteStream on: (self new: size))
limit: size - 2;
limitBlock: [
^ out originalContents
at: size - 1 put: $.;
at: size put: Character cr;
yourself ].
[
out << self loremIpsum; cr; cr.
5 atRandom timesRepeat: [
15 atRandom timesRepeat: [
out << words atRandom capitalized.
20 atRandom timesRepeat: [ out space; << words atRandom ].
out nextPut: $.; space ].
out cr; cr ] ] repeat
]
{ #category : 'instance creation' }
String class >> new: sizeRequested [
"Return a new instance with the number of indexable variables specified by the argument."
^ self == String
ifTrue: [ ByteString new: sizeRequested ]
ifFalse: [ self basicNew: sizeRequested ]
]
{ #category : 'private - accessing' }
String class >> newAsciiOrder [
^ (0 to: 255) as: ByteArray
]
{ #category : 'private - accessing' }
String class >> newCSLineEnders [
"CR and LF--characters that terminate a line"
^ CharacterSet crlf
]
{ #category : 'private - accessing' }
String class >> newCaseInsensitiveOrder [
"map char and char asLower (Lowercase Latin1 stays in the Latin1 range, uppercase not.)"
| newCollection |
newCollection := AsciiOrder copy.
(0 to: 255) do:[ :v |
| char lower |
char := v asCharacter.
lower := char asLowercase.
newCollection at: lower asciiValue + 1 put: (newCollection at: char asciiValue + 1) ].
^ newCollection
]
{ #category : 'private - accessing' }
String class >> newCaseSensitiveOrder [
"Case-sensitive compare sorts space, digits, letters, all the rest..."
| newTab order |
newTab := ByteArray new: 256 withAll: 255.
order := -1.
' 0123456789' do: "0..10"
[:c | newTab at: c asciiValue + 1 put: (order := order+1)].
($a to: $z) do: "11-64"
[:c | newTab at: c asUppercase asciiValue + 1 put: (order := order+1).
newTab at: c asciiValue + 1 put: (order := order+1)].
1 to: newTab size do:
[:i | (newTab at: i) = 255 ifTrue:
[newTab at: i put: (order := order+1)]].
order = 255 ifFalse: [self error: 'order problem'].
^ newTab
]
{ #category : 'private - accessing' }
String class >> newLowercasingTable [
"a table for translating to lower case"
^ String withAll: (Character allByteCharacters collect: [:c | c asLowercase])
]
{ #category : 'private - accessing' }
String class >> newTokenish [
"a table for testing tokenish (for fast numArgs)"
^ String withAll: (Character allByteCharacters
collect: [:c | c tokenish ifTrue: [ c ] ifFalse: [ $~ ]])
]
{ #category : 'private - accessing' }
String class >> newUppercasingTable [
"a table for translating to upper case"
^ String withAll: (Character allByteCharacters collect: [:c | c asUppercase])
]
{ #category : 'instance creation' }
String class >> readFrom: inStream [
"Answer an instance of me that is determined by reading the stream,
inStream. Embedded double quotes become the quote Character."
| char done |
^ self streamContents: [ :outStream |
"go to first quote"
inStream skipTo: $'.
done := false.
[ done or: [ inStream atEnd ] ]
whileFalse: [
char := inStream next.
char = $'
ifTrue: [
char := inStream next.
char = $'
ifTrue: [ outStream nextPut: char ]
ifFalse: [ done := true ] ]
ifFalse: [ outStream nextPut: char ] ] ]
]
{ #category : 'instance creation' }
String class >> space [
"Answer a string containing a single space character."
^ self with: Character space
]
{ #category : 'primitives' }
String class >> stringHash: aString initialHash: speciesHash [
| stringSize hash low |
stringSize := aString size.
hash := speciesHash bitAnd: 16rFFFFFFF.
1 to: stringSize do: [:pos |
hash := hash + (aString basicAt: pos).
"Begin hashMultiply"
low := hash bitAnd: 16383.
hash := (16r260D * low + ((16r260D * (hash // 16384) + (16r0065 * low) bitAnd: 16383) * 16384)) bitAnd: 16r0FFFFFFF.
].
^ hash
]
{ #category : 'instance creation' }
String class >> tab [
"Answer a string containing a single tab character."
^ self with: Character tab
]
{ #category : 'primitives' }
String class >> translate: aString from: start to: stop table: table [
"Trivial, non-primitive version"
| char |
start to: stop do: [:i |
(char := aString basicAt: i) < 256 ifTrue: [
aString at: i put: (table at: char+1)].
]
]
{ #category : 'accessing' }
String class >> typeTable [
TypeTable ifNil: [self initializeTypeTable].
^ TypeTable
]
{ #category : 'instance creation' }
String class >> value: anInteger [
^ self with: (Character value: anInteger)
]
{ #category : 'instance creation' }
String class >> with: aCharacter [
| newCollection |
newCollection := aCharacter asInteger < 256
ifTrue:[ ByteString new: 1]
ifFalse:[ WideString new: 1].
newCollection at: 1 put: aCharacter.
^newCollection
]
{ #category : 'comparing' }
String >> < aString [
"Answer whether the receiver sorts before aString.
The collation order is simple ascii (with case differences)."
" 'abc' < 'def' >>> true"
" 'abc' < 'abc' >>> false"
" 'def' < 'abc' >>> false"
^ (self compare: self with: aString) < 0
]
{ #category : 'comparing' }
String >> <= aString [
"Answer whether the receiver sorts before or equal to aString.
The collation order is simple ascii (with case differences)."
" 'abc' <= 'def' >>> true"
" 'abc' <= 'abc' >>> true"
" 'def' <= 'abc' >>> false"
^ (self compare: self with: aString) <= 0
]
{ #category : 'comparing' }
String >> = aString [
"Answer whether the receiver sorts equally as aString.
The collation order is simple ascii (with case differences)."
" 'abc' = 'def' >>> false"
" 'abc' = 'abc' >>> true"
" 'def' = 'abc' >>> false"
(aString isString and: [ self size = aString size ]) ifFalse: [ ^ false ].
^ (self compare: self with: aString) = 0
]
{ #category : 'comparing' }
String >> > aString [
"Answer whether the receiver sorts after aString.
The collation order is simple ascii (with case differences)."
" 'def' > 'abc' >>> true"
" 'def' > 'def' >>> false"
" 'abc' > 'def' >>> false"
^ (self compare: self with: aString) > 0
]
{ #category : 'comparing' }
String >> >= aString [
"Answer whether the receiver sorts after or equal to aString.
The collation order is simple ascii (with case differences)."
" 'def' >= 'abc' >>> true"
" 'def' >= 'def' >>> true"
" 'abc' >= 'def' >>> false"
^ (self compare: self with: aString) >= 0
]
{ #category : 'comparing' }
String >> alike: aString [
"Answer some indication of how alike the receiver is to the argument, 0 is no match, twice aString size is best score (but see example with 7). Case is ignored. This method is used to help find mistyped variable names in methods."
"('abc' alike: 'abc') >>> 7."
"('action' alike: 'actions') >>> 7."
"('action' alike: 'caption') >>> 5."
"('action' alike: 'name') >>> 0."
| i j k minSize bonus |
minSize := (j := self size) min: (k := aString size).
bonus := (j - k) abs < 2 ifTrue: [ 1 ] ifFalse: [ 0 ].
i := 1.
[(i <= minSize) and: [((self at: i) asInteger bitAnd: 16rDF) = ((aString at: i) asciiValue bitAnd: 16rDF)]]
whileTrue: [ i := i + 1 ].
[(j > 0) and: [(k > 0) and:
[((self at: j) asInteger bitAnd: 16rDF) = ((aString at: k) asciiValue bitAnd: 16rDF)]]]
whileTrue: [ j := j - 1. k := k - 1. ].
^ i - 1 + self size - j + bonus
]
{ #category : 'finding/searching' }
String >> allRangesOfSubstring: aSubstring [
"('Ab cd ef Ab cd' allRangesOfSubstring: 'cd') >>> {(4 to: 5). (13 to: 14)}"
"('Ab cd ef Ab cd' allRangesOfSubstring: 'zz') >>> #()"
^ Array streamContents: [:s | | start subSize |
start := 1.
subSize := aSubstring size.
[start isZero]
whileFalse: [ start := self findString: aSubstring startingAt: start.
start > 0
ifTrue: [s nextPut: (start to: start + subSize - 1).
start := start + subSize]]]
]
{ #category : 'converting' }
String >> asByteArray [
"Convert to a ByteArray with the ascii values of the string."
"'a' asByteArray >>> #[97]"
"'A' asByteArray >>> #[65]"
"'ABA' asByteArray >>> #[65 66 65]"
self subclassResponsibility
]
{ #category : 'converting' }
String >> asByteString [
"Convert the receiver into a ByteString, if possible"
"Do not raise an error if it's not possible, since my use case is usually one in which WideStrings may or may not have been mutated to something representable in a ByteString, and we mostly do this to save space if possible. If the percentage of such cases are small, it may be better to use isOctetString check first to avoid creating String instances"
^self asOctetString
]
{ #category : 'converting' }
String >> asCamelCase [
"Convert to CamelCase, i.e, remove spaces, and convert starting lowercase to uppercase."
"'A man, a plan, a canal, panama' asCamelCase >>> 'AMan,APlan,ACanal,Panama'"
"'Here 123should % be 6 the name6 of the method' asCamelCase >>> 'Here123should%Be6TheName6OfTheMethod'"
^ self species streamContents: [:stream |
self substrings do: [:sub |
stream nextPutAll: sub capitalized]]
]
{ #category : 'converting' }
String >> asComment [
"return this string, munged so that it can be treated as a comment in Smalltalk code. Quote marks are added to the beginning and end of the string, and whenever a solitary quote mark appears within the string, it is doubled"
^ String streamContents: [ :str |
| quoteCount first |
str nextPut: $".
quoteCount := 0.
first := true.
self withIndexDo: [ :char :index |
char = $"
ifTrue: [
(first or: (index = self size) ) ifFalse: [
str nextPut: char.
quoteCount := quoteCount + 1 ] ]
ifFalse: [
quoteCount odd ifTrue: [ "add a quote to even the number of quotes in a row"
str nextPut: $" ].
quoteCount := 0.
str nextPut: char ].
first := false ].
quoteCount odd
ifTrue: [ "check at the end" str nextPut: $" ].
str nextPut: $" ]
]
{ #category : 'converting' }
String >> asDate [
"Many allowed forms, see Date>>#readFrom:"
self deprecated: 'Use Date>>#readFrom:pattern: specifying a concrete pattern instead.'.
^ Date fromString: self
]
{ #category : 'converting' }
String >> asDateAndTime [
"Convert from UTC format"
^ DateAndTime fromString: self
]
{ #category : 'converting' }
String >> asDuration [
"Convert from [-]D:HH:MM:SS[.S] format. What is between [] implies optional elements"
^ Duration fromString: self
]
{ #category : 'accessing' }
String >> asFileName [
"Answer a String made up from the receiver that is an acceptable file name."
| string checkedString |
string := FileSystem disk checkName: self fixErrors: true.
checkedString := FilePathEncoder encode: string.
^ FilePathEncoder decode: checkedString
]
{ #category : 'converting' }
String >> asFourCode [
"'abcd' asFourCode >>> -513645724"
"'1111' asFourCode >>> 825307441"
"'1234' asFourCode >>> 825373492"
| result |
self size = 4
ifFalse: [^self error: 'must be exactly four characters'].
result := self inject: 0 into: [:val :each | 256 * val + each asciiValue ].
(result bitAnd: 16r80000000) = 0
ifFalse: [ Error signal: 'cannot resolve fourcode' ].
(result bitAnd: 16r40000000) = 0
ifFalse: [ ^ result - 16r80000000 ].
^ result
]
{ #category : 'converting' }
String >> asHTMLString [
"substitute the < & > into HTML compliant elements"
"'<a>' asHTMLString"
^ self species new: self size streamContents: [ :s|
self do: [:c | s nextPutAll: c asHTMLString ]]
]
{ #category : 'converting' }
String >> asHex [
"'A' asHex >>> '16r41'"
"'AA' asHex >>> '16r4116r41'"
^ self species new: self size * 4 streamContents: [ :stream |
self do: [ :ch | stream nextPutAll: ch hex ]]
]
{ #category : 'converting' }
String >> asInteger [
"Return the integer present in the receiver, or nil. In case of float, returns the integer part."
"'1' asInteger >>> 1"
"'-1' asInteger >>> -1"
"'10' asInteger >>> 10"
"'a' asInteger >>> nil"
"'1.234' asInteger >>> 1"
^self asSignedInteger
]
{ #category : 'converting' }
String >> asLowercase [
"Answer a String made up from the receiver whose characters are all lowercase."
"'PhaRo' asLowercase >>> 'pharo'"
"'' asLowercase >>> ''"
"' ' asLowercase >>> ' '"
^ self copy asString translateToLowercase
]
{ #category : 'converting' }
String >> asNumber [
"Answer the Number created by interpreting the receiver as the string representation of a number."
^ Number readFromString: self
]
{ #category : 'converting' }
String >> asOctetString [
"Convert the receiver into an octet string, if possible"
"(IE, I am a WideString containing only character with codePoints < 255, so all of them fit in a latin1-string)."
| string |
string := String new: self size.
1 to: self size do: [:i | string at: i put: (self at: i)].
^string
]
{ #category : 'converting' }
String >> asPluralBasedOn: aNumberOrCollection [
"Append an 's' to this string based on whether aNumberOrCollection is 1 or of size 1."
^ (aNumberOrCollection = 1 or:
[aNumberOrCollection isCollection and: [aNumberOrCollection size = 1]])
ifTrue: [self]
ifFalse: [self, 's']
]
{ #category : 'converting' }
String >> asSignedInteger [
"Returns the first signed integer it can find or nil."
| start stream |
start := self findFirst: [:char | char isDigit].
start isZero ifTrue: [^ nil].
stream := self readStream position: start - 1.
((stream position ~= 0) and: [stream peekBack = $-])
ifTrue: [stream back].
^ Integer readFrom: stream
]
{ #category : 'converting' }
String >> asString [
"Answer this string."
^ self
]
{ #category : 'converting' }
String >> asSymbol [
"Answer the unique Symbol whose characters are the characters of the string."
^Symbol intern: self
]
{ #category : 'converting' }
String >> asTime [
"Many allowed forms, see Time>>readFrom:"
^ Time fromString: self
]
{ #category : 'converting' }
String >> asUnsignedInteger [
"Returns the first integer it can find or nil."
| start stream |
start := self findFirst: [ :char | char isDigit ].
start isZero ifTrue: [ ^ nil ].
stream := self readStream position: start - 1.
^ Integer readFrom: stream
]
{ #category : 'converting' }
String >> asUppercase [
"Answer a String made up from the receiver whose characters are all uppercase."
"'pharo' asUppercase >>> 'PHARO'"
"'' asUppercase >>> ''"
"' ' asUppercase >>> ' '"
^self copy asString translateToUppercase
]
{ #category : 'converting' }
String >> asValidSelector [
"Returns a symbol that is a valid selector by removing any space or forbidden characters"
"'234znak ::x43 ''åå) _ : 2' asValidSelector >>> #'v234znak:x43:v2'"
"'234znak ::x43 åå) :2' asValidSelector >>> #v234znak:x43:v2"
^(((
$: join: (
(
$: split: (
self select: [ :char |
(char charCode < 128) and: [
char isAlphaNumeric or: [
char = $:
]
]
]
)
)
select: [ :split | split isNotEmpty ]
thenCollect: [ :nonEmptyString |
nonEmptyString first isLetter
ifTrue: [ nonEmptyString uncapitalized ]
ifFalse: [ 'v' , nonEmptyString ]
]
)
) ifEmpty: [ 'v' ]), ((self isNotEmpty and: [ self last = $: ]) ifTrue: [ ':' ] ifFalse: [ #() ]) )asSymbol
]
{ #category : 'converting' }
String >> asWideString [
^ WideString from: self
]
{ #category : 'testing' }
String >> beginsWith: prefix [
"Answer whether the receiver begins with the given prefix string.
The comparison is case-sensitive."
"IMPLEMENTATION NOTE:
following algorithm is optimized in primitive only in case self and prefix are bytes like.
Otherwise, if self is wide, then super outperforms,
Otherwise, if prefix is wide, primitive is not correct"
"('pharo' beginsWith: '') >>> true"
"('pharo' beginsWith: 'pharo-project') >>> false"
"('pharo' beginsWith: 'phuro') >>> false"
"('pharo' beginsWith: 'pha') >>> true"
prefix ifEmpty: [ ^true ].
(self class isBytes and: [ prefix class isBytes ]) ifFalse: [^super beginsWith: prefix].
self size < prefix size ifTrue: [^ false].
^ (self findSubstring: prefix in: self startingAt: 1
matchTable: CaseSensitiveOrder) = 1
]
{ #category : 'testing' }
String >> beginsWith: prefix caseSensitive: aBoolean [
"Answer whether the receiver begins with the given prefix string"
"IMPLEMENTATION NOTE:
following algorithm is optimized in primitive only in case self and prefix are bytes like.
Otherwise, if self or prefix are wide strings, then slow version with asLowercase convertation,
(primitive is not correct for wide strings)"
"('pharo' beginsWith: '' caseSensitive: false) >>> true"
"('pharo' beginsWith: 'pharo-project' caseSensitive: false) >>> false"
"('pharo' beginsWith: 'phuro' caseSensitive: false) >>> false"
"('pharo' beginsWith: 'Pha' caseSensitive: false) >>> true"
prefix ifEmpty: [ ^true ].
aBoolean ifTrue: [ ^self beginsWith: prefix ].
self size < prefix size ifTrue: [^ false].
(self class isBytes and: [prefix class isBytes]) ifTrue: [
"Optimized version based on primitive"
^ (self findSubstring: prefix in: self startingAt: 1 matchTable: CaseInsensitiveOrder) = 1 ].
prefix withIndexDo: [ :each :index |
(self at: index) asLowercase = each asLowercase ifFalse: [ ^false ]
].
^true
]
{ #category : 'accessing' }
String >> byteAt: index [
^self subclassResponsibility
]
{ #category : 'accessing' }
String >> byteAt: index put: value [
^self subclassResponsibility
]
{ #category : 'accessing' }
String >> byteSize [
^self subclassResponsibility
]
{ #category : 'converting' }
String >> capitalized [
"Return a copy with the first letter capitalized"
"'abc' capitalized >>> 'Abc'"
| cap |
self isEmpty ifTrue: [ ^self copy ].
cap := self copy.
cap at: 1 put: (cap at: 1) asUppercase.
^ cap
]
{ #category : 'comparing' }
String >> caseInsensitiveLessOrEqual: aString [
"Answer whether the receiver sorts before or equal to aString.
The collation order is case insensitive."
^(self compare: aString caseSensitive: false) <= 2
]
{ #category : 'comparing' }
String >> caseSensitiveLessOrEqual: aString [
"Answer whether the receiver sorts before or equal to aString.
The collation order is case sensitive."
^(self compare: aString caseSensitive: true) <= 2
]
{ #category : 'comparing' }
String >> charactersExactlyMatching: aString [
"Do a character-by-character comparison between the receiver and aString. Return the index of the final character that matched exactly."
"('s' charactersExactlyMatching: 'abc') >>> 0"
"('fear is the little death that the.' charactersExactlyMatching: 'the') >>> 0"
"('fear is the little death that the.' charactersExactlyMatching: 'fear is') >>> 7"
| count |
count := self size min: aString size.
1 to: count do: [:i |
(self at: i) = (aString at: i) ifFalse: [
^ i - 1]].
^ count
]
{ #category : 'comparing' }
String >> compare: aString [
"Answer a comparison code telling how the receiver sorts relative to aString:
1 - before
2 - equal
3 - after.
The collation sequence is ascii with case differences ignored.
To get the effect of a <= b, but ignoring case, use (a compare: b) <= 2."
"('aa' compare: 'ab') >>> 1"
"('aa' compare: 'aa') >>> 2"
"('ab' compare: 'aa') >>> 3"
^self compare: aString caseSensitive: false
]
{ #category : 'comparing' }
String >> compare: aString caseSensitive: aBool [
"Answer a comparison code telling how the receiver sorts relative to aString:
1 - before
2 - equal
3 - after.
"
| map |
map := aBool
ifTrue: [ CaseSensitiveOrder ]
ifFalse: [ CaseInsensitiveOrder ].
^ (self compare: self with: aString collated: map) sign + 2
]
{ #category : 'verification' }
String >> compare: string1 with: string2 [
(string1 isByteString and: [ string2 isByteString ]) ifTrue: [
^ string1 compareWith: string2 "Not giving the order allows to use the jitted version of the primitive" ].
"Primitive does not fail properly right now"
^ String compare: string1 with: string2 collated: AsciiOrder
]
{ #category : 'comparing' }
String >> compare: string1 with: string2 collated: order [
"'abc' = 'abc' asWideString >>> true"
"'abc' asWideString = 'abc' >>> true"
"(ByteArray with: 97 with: 0 with: 0 with: 0) asString ~= 'a000' asWideString >>> true"
"('abc' sameAs: 'aBc' asWideString) >>> true"
"('aBc' asWideString sameAs: 'abc') >>> true"
"('a000' asWideString ~= (ByteArray with: 97 with: 0 with: 0 with: 0) asString) >>> true"
"((ByteArray with: 97 with: 0 with: 0 with: 0) asString sameAs: 'Abcd' asWideString) >>> false"
"('a000' asWideString sameAs: (ByteArray with: 97 with: 0 with: 0 with: 0) asString) >>> false"
(string1 isByteString and: [ string2 isByteString ]) ifTrue: [ ^ string1 compareWith: string2 collated: order ].
"Primitive does not fail properly right now"