• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

enetx / g / 14821882949

04 May 2025 01:51PM UTC coverage: 87.23% (+0.9%) from 86.333%
14821882949

push

github

enetx
unsafe ref

4 of 4 new or added lines in 1 file covered. (100.0%)

74 existing lines in 10 files now uncovered.

3347 of 3837 relevant lines covered (87.23%)

132.15 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.82
/string.go
1
package g
2

3
import (
4
        "fmt"
5
        "math/big"
6
        "strconv"
7
        "strings"
8
        "unicode"
9
        "unicode/utf8"
10
        "unsafe"
11

12
        "github.com/enetx/g/cmp"
13
        "github.com/enetx/g/f"
14
        "golang.org/x/text/unicode/norm"
15
)
16

17
// NewString creates a new String from the provided string.
18
func NewString[T ~string | rune | byte | ~[]rune | ~[]byte](str T) String { return String(str) }
303✔
19

20
// Clone returns a copy of the String.
21
// It ensures that the returned String does not share underlying memory with the original String,
22
// making it safe to modify or store independently.
UNCOV
23
func (s String) Clone() String { return String(strings.Clone(s.Std())) }
×
24

25
// Transform applies a transformation function to the String and returns the result.
26
func (s String) Transform(fn func(String) String) String { return fn(s) }
1✔
27

28
// Builder returns a new Builder initialized with the content of the String.
29
func (s String) Builder() *Builder { return NewBuilder().Write(s) }
1✔
30

31
// Min returns the minimum of Strings.
32
func (s String) Min(b ...String) String { return cmp.Min(append(b, s)...) }
3✔
33

34
// Max returns the maximum of Strings.
35
func (s String) Max(b ...String) String { return cmp.Max(append(b, s)...) }
3✔
36

37
// Random generates a random String of the specified length, selecting characters from predefined sets.
38
// If additional character sets are provided, only those will be used; the default set (ASCII_LETTERS and DIGITS)
39
// is excluded unless explicitly provided.
40
//
41
// Parameters:
42
// - count (Int): Length of the random String to generate.
43
// - letters (...String): Additional character sets to consider for generating the random String (optional).
44
//
45
// Returns:
46
// - String: Randomly generated String with the specified length.
47
//
48
// Example usage:
49
//
50
//        randomString := g.String.Random(10)
51
//        randomString contains a random String with 10 characters.
52
func (String) Random(length Int, letters ...String) String {
300✔
53
        var chars Slice[rune]
300✔
54

300✔
55
        if len(letters) != 0 {
300✔
56
                chars = letters[0].Runes()
×
57
        } else {
300✔
58
                chars = (ASCII_LETTERS + DIGITS).Runes()
300✔
59
        }
300✔
60

61
        result := NewBuilder()
300✔
62

300✔
63
        for range length {
12,457✔
64
                result.WriteRune(chars.Random())
12,157✔
65
        }
12,157✔
66

67
        return result.String()
300✔
68
}
69

70
// IsASCII checks if all characters in the String are ASCII bytes.
71
func (s String) IsASCII() bool {
8✔
72
        for _, r := range s {
72✔
73
                if r > unicode.MaxASCII {
67✔
74
                        return false
3✔
75
                }
3✔
76
        }
77

78
        return true
5✔
79
}
80

81
// IsDigit checks if all characters in the String are digits.
82
func (s String) IsDigit() bool {
4✔
83
        if s.Empty() {
5✔
84
                return false
1✔
85
        }
1✔
86

87
        for _, c := range s {
14✔
88
                if !unicode.IsDigit(c) {
12✔
89
                        return false
1✔
90
                }
1✔
91
        }
92

93
        return true
2✔
94
}
95

96
// ToInt tries to parse the String as an int and returns an Int.
97
func (s String) ToInt() Result[Int] {
210✔
98
        hint, err := strconv.ParseInt(s.Std(), 0, 32)
210✔
99
        if err != nil {
256✔
100
                return Err[Int](err)
46✔
101
        }
46✔
102

103
        return Ok(Int(hint))
164✔
104
}
105

106
// ToBigInt attempts to convert the String receiver into an Option containing a *big.Int.
107
// This function assumes the string represents a numerical value, which can be in decimal,
108
// hexadecimal (prefixed with "0x"), or octal (prefixed with "0") format. The function
109
// leverages the SetString method of the math/big package, automatically detecting the
110
// numeric base when set to 0.
111
//
112
// If the string is correctly formatted and represents a valid number, ToBigInt returns
113
// a Some containing the *big.Int parsed from the string. If the string is empty, contains
114
// invalid characters, or does not conform to a recognizable numeric format, ToBigInt
115
// returns a None, indicating that the conversion was unsuccessful.
116
//
117
// Returns:
118
//   - An Option[*big.Int] encapsulating the conversion result. It returns Some[*big.Int]
119
//     with the parsed value if successful, otherwise None[*big.Int] if the parsing fails.
120
func (s String) ToBigInt() Option[*big.Int] {
5✔
121
        if bigInt, ok := new(big.Int).SetString(s.Std(), 0); ok {
8✔
122
                return Some(bigInt)
3✔
123
        }
3✔
124

125
        return None[*big.Int]()
2✔
126
}
127

128
// ToFloat tries to parse the String as a float64 and returns an Float.
129
func (s String) ToFloat() Result[Float] {
8✔
130
        float, err := strconv.ParseFloat(s.Std(), 64)
8✔
131
        if err != nil {
13✔
132
                return Err[Float](err)
5✔
133
        }
5✔
134

135
        return Ok(Float(float))
3✔
136
}
137

138
// Title converts the String to title case.
139
func (s String) Title() String { return String(title.String(s.Std())) }
29✔
140

141
// Lower returns the String in lowercase.
142
func (s String) Lower() String { return s.Bytes().Lower().String() }
7✔
143

144
// Upper returns the String in uppercase.
145
func (s String) Upper() String { return s.Bytes().Upper().String() }
8✔
146

147
// Trim removes leading and trailing white space from the String.
148
func (s String) Trim() String { return String(strings.TrimSpace(s.Std())) }
209✔
149

150
// TrimStart removes leading white space from the String.
151
func (s String) TrimStart() String { return String(strings.TrimLeftFunc(s.Std(), unicode.IsSpace)) }
5✔
152

153
// TrimEnd removes trailing white space from the String.
154
func (s String) TrimEnd() String { return String(strings.TrimRightFunc(s.Std(), unicode.IsSpace)) }
11✔
155

156
// TrimSet removes the specified set of characters from both the beginning and end of the String.
157
func (s String) TrimSet(cutset String) String { return String(strings.Trim(s.Std(), cutset.Std())) }
9✔
158

159
// TrimStartSet removes the specified set of characters from the beginning of the String.
160
func (s String) TrimStartSet(cutset String) String {
5✔
161
        return String(strings.TrimLeft(s.Std(), cutset.Std()))
5✔
162
}
5✔
163

164
// TrimEndSet removes the specified set of characters from the end of the String.
165
func (s String) TrimEndSet(cutset String) String {
5✔
166
        return String(strings.TrimRight(s.Std(), cutset.Std()))
5✔
167
}
5✔
168

169
// StripPrefix trims the specified prefix from the String.
170
func (s String) StripPrefix(prefix String) String {
4✔
171
        return String(strings.TrimPrefix(s.Std(), prefix.Std()))
4✔
172
}
4✔
173

174
// StripSuffix trims the specified suffix from the String.
175
func (s String) StripSuffix(suffix String) String {
13✔
176
        return String(strings.TrimSuffix(s.Std(), suffix.Std()))
13✔
177
}
13✔
178

179
// Replace replaces the 'oldS' String with the 'newS' String for the specified number of
180
// occurrences.
181
func (s String) Replace(oldS, newS String, n Int) String {
6✔
182
        return String(strings.Replace(s.Std(), oldS.Std(), newS.Std(), n.Std()))
6✔
183
}
6✔
184

185
// ReplaceAll replaces all occurrences of the 'oldS' String with the 'newS' String.
186
func (s String) ReplaceAll(oldS, newS String) String {
5✔
187
        return String(strings.ReplaceAll(s.Std(), oldS.Std(), newS.Std()))
5✔
188
}
5✔
189

190
// ReplaceMulti creates a custom replacer to perform multiple string replacements.
191
//
192
// Parameters:
193
//
194
// - oldnew ...String: Pairs of strings to be replaced. Specify as many pairs as needed.
195
//
196
// Returns:
197
//
198
// - String: A new string with replacements applied using the custom replacer.
199
//
200
// Example usage:
201
//
202
//        original := g.String("Hello, world! This is a test.")
203
//        replaced := original.ReplaceMulti(
204
//            "Hello", "Greetings",
205
//            "world", "universe",
206
//            "test", "example",
207
//        )
208
//        // replaced contains "Greetings, universe! This is an example."
209
func (s String) ReplaceMulti(oldnew ...String) String {
4✔
210
        pairs := TransformSlice(Slice[String](oldnew), String.Std)
4✔
211
        return String(strings.NewReplacer(pairs...).Replace(s.Std()))
4✔
212
}
4✔
213

214
// Remove removes all occurrences of specified substrings from the String.
215
//
216
// Parameters:
217
//
218
// - matches ...String: Substrings to be removed from the string. Specify as many substrings as needed.
219
//
220
// Returns:
221
//
222
// - String: A new string with all specified substrings removed.
223
//
224
// Example usage:
225
//
226
//        original := g.String("Hello, world! This is a test.")
227
//        modified := original.Remove(
228
//            "Hello",
229
//            "test",
230
//        )
231
//        // modified contains ", world! This is a ."
232
func (s String) Remove(matches ...String) String {
3✔
233
        pairs := TransformSlice(Slice[String](matches).Iter().Intersperse("").Collect().Append(""), String.Std)
3✔
234
        return String(strings.NewReplacer(pairs...).Replace(s.Std()))
3✔
235
}
3✔
236

237
// ReplaceNth returns a new String instance with the nth occurrence of oldS
238
// replaced with newS. If there aren't enough occurrences of oldS, the
239
// original String is returned. If n is less than -1, the original String
240
// is also returned. If n is -1, the last occurrence of oldS is replaced with newS.
241
//
242
// Returns:
243
//
244
// - A new String instance with the nth occurrence of oldS replaced with newS.
245
//
246
// Example usage:
247
//
248
//        s := g.String("The quick brown dog jumped over the lazy dog.")
249
//        result := s.ReplaceNth("dog", "fox", 2)
250
//        fmt.Println(result)
251
//
252
// Output: "The quick brown dog jumped over the lazy fox.".
253
func (s String) ReplaceNth(oldS, newS String, n Int) String {
18✔
254
        if n < -1 || len(oldS) == 0 {
21✔
255
                return s
3✔
256
        }
3✔
257

258
        count, i := Int(0), Int(0)
15✔
259

15✔
260
        for {
35✔
261
                pos := s[i:].Index(oldS)
20✔
262
                if pos == -1 {
24✔
263
                        break
4✔
264
                }
265

266
                pos += i
16✔
267
                count++
16✔
268

16✔
269
                if count == n || (n == -1 && s[pos+oldS.Len():].Index(oldS) == -1) {
27✔
270
                        return s[:pos] + newS + s[pos+oldS.Len():]
11✔
271
                }
11✔
272

273
                i = pos + oldS.Len()
5✔
274
        }
275

276
        return s
4✔
277
}
278

279
// Contains checks if the String contains the specified substring.
280
func (s String) Contains(substr String) bool { return f.Contains(substr)(s) }
10✔
281

282
// ContainsAny checks if the String contains any of the specified substrings.
283
func (s String) ContainsAny(substrs ...String) bool {
4✔
284
        return Slice[String](substrs).
4✔
285
                Iter().
4✔
286
                Any(func(substr String) bool { return s.Contains(substr) })
9✔
287
}
288

289
// ContainsAll checks if the given String contains all the specified substrings.
290
func (s String) ContainsAll(substrs ...String) bool {
4✔
291
        return Slice[String](substrs).
4✔
292
                Iter().
4✔
293
                All(func(substr String) bool { return s.Contains(substr) })
9✔
294
}
295

296
// ContainsAnyChars checks if the String contains any characters from the specified String.
297
func (s String) ContainsAnyChars(chars String) bool { return f.ContainsAnyChars(chars)(s) }
5✔
298

299
// StartsWith checks if the String starts with the specified prefix.
300
// It uses a higher-order function to perform the check.
301
func (s String) StartsWith(prefix String) bool { return f.StartsWith(prefix)(s) }
7✔
302

303
// StartsWithAny checks if the String starts with any of the provided prefixes.
304
// The method accepts a variable number of arguments, allowing for checking against multiple
305
// prefixes at once. It iterates over the provided prefixes and uses the HasPrefix function from
306
// the strings package to check if the String starts with each prefix.
307
// The function returns true if the String starts with any of the prefixes, and false otherwise.
308
//
309
// Example usage:
310
//
311
//        s := g.String("http://example.com")
312
//        if s.StartsWithAny("http://", "https://") {
313
//           // do something
314
//        }
315
func (s String) StartsWithAny(prefixes ...String) bool {
5✔
316
        return Slice[String](prefixes).
5✔
317
                Iter().
5✔
318
                Any(func(prefix String) bool { return s.StartsWith(prefix) })
12✔
319
}
320

321
// EndsWith checks if the String ends with the specified suffix.
322
// It uses a higher-order function to perform the check.
323
func (s String) EndsWith(suffix String) bool { return f.EndsWith(suffix)(s) }
5✔
324

325
// EndsWithAny checks if the String ends with any of the provided suffixes.
326
// The method accepts a variable number of arguments, allowing for checking against multiple
327
// suffixes at once. It iterates over the provided suffixes and uses the HasSuffix function from
328
// the strings package to check if the String ends with each suffix.
329
// The function returns true if the String ends with any of the suffixes, and false otherwise.
330
//
331
// Example usage:
332
//
333
//        s := g.String("example.com")
334
//        if s.EndsWithAny(".com", ".net") {
335
//           // do something
336
//        }
337
func (s String) EndsWithAny(suffixes ...String) bool {
3✔
338
        return Slice[String](suffixes).
3✔
339
                Iter().
3✔
340
                Any(func(suffix String) bool { return s.EndsWith(suffix) })
8✔
341
}
342

343
// Lines splits the String by lines and returns the iterator.
344
func (s String) Lines() SeqSlice[String] {
2✔
345
        return transformSeq(strings.Lines(s.Std()), NewString).Map(String.TrimEnd)
2✔
346
}
2✔
347

348
// Fields splits the String into a slice of substrings, removing any whitespace, and returns the iterator.
349
func (s String) Fields() SeqSlice[String] {
4✔
350
        return transformSeq(strings.FieldsSeq(s.Std()), NewString)
4✔
351
}
4✔
352

353
// FieldsBy splits the String into a slice of substrings using a custom function to determine the field boundaries,
354
// and returns the iterator.
355
func (s String) FieldsBy(fn func(r rune) bool) SeqSlice[String] {
3✔
356
        return transformSeq(strings.FieldsFuncSeq(s.Std(), fn), NewString)
3✔
357
}
3✔
358

359
// Split splits the String by the specified separator and returns the iterator.
360
func (s String) Split(sep ...String) SeqSlice[String] {
99✔
361
        var separator String
99✔
362
        if len(sep) != 0 {
191✔
363
                separator = sep[0]
92✔
364
        }
92✔
365

366
        return transformSeq(strings.SplitSeq(s.Std(), separator.Std()), NewString)
99✔
367
}
368

369
// SplitAfter splits the String after each instance of the specified separator and returns the iterator.
370
func (s String) SplitAfter(sep String) SeqSlice[String] {
8✔
371
        return transformSeq(strings.SplitAfterSeq(s.Std(), sep.Std()), NewString)
8✔
372
}
8✔
373

374
// SplitN splits the String into substrings using the provided separator and returns an Slice[String] of the results.
375
// The n parameter controls the number of substrings to return:
376
// - If n is negative, there is no limit on the number of substrings returned.
377
// - If n is zero, an empty Slice[String] is returned.
378
// - If n is positive, at most n substrings are returned.
379
func (s String) SplitN(sep String, n Int) Slice[String] {
3✔
380
        return TransformSlice(strings.SplitN(s.Std(), sep.Std(), n.Std()), NewString)
3✔
381
}
3✔
382

383
// Chunks splits the String into chunks of the specified size.
384
//
385
// This function iterates through the String, creating new String chunks of the specified size.
386
// If size is less than or equal to 0 or the String is empty,
387
// it returns an empty Slice[String].
388
// If size is greater than or equal to the length of the String,
389
// it returns an Slice[String] containing the original String.
390
//
391
// Parameters:
392
//
393
// - size (Int): The size of the chunks to split the String into.
394
//
395
// Returns:
396
//
397
// - Slice[String]: A slice of String chunks of the specified size.
398
//
399
// Example usage:
400
//
401
//        text := g.String("Hello, World!")
402
//        chunks := text.Chunks(4)
403
//
404
// chunks contains {"Hell", "o, W", "orld", "!"}.
405
func (s String) Chunks(size Int) SeqSlice[String] {
6✔
406
        if size.Lte(0) || s.Empty() {
8✔
407
                return func(func(String) bool) {}
4✔
408
        }
409

410
        runes := []rune(s)
4✔
411
        if size.Gte(Int(len(runes))) {
6✔
412
                return func(yield func(String) bool) { yield(s) }
4✔
413
        }
414

415
        n := size.Std()
2✔
416
        return func(yield func(String) bool) {
4✔
417
                for i := 0; i < len(runes); i += n {
9✔
418
                        end := min(i+n, len(runes))
7✔
419
                        if !yield(String(runes[i:end])) {
7✔
UNCOV
420
                                return
×
UNCOV
421
                        }
×
422
                }
423
        }
424
}
425

426
// Cut returns two String values. The first String contains the remainder of the
427
// original String after the cut. The second String contains the text between the
428
// first occurrences of the 'start' and 'end' strings, with tags removed if specified.
429
//
430
// The function searches for the 'start' and 'end' strings within the String.
431
// If both are found, it returns the first String containing the remainder of the
432
// original String after the cut, followed by the second String containing the text
433
// between the first occurrences of 'start' and 'end' with tags removed if specified.
434
//
435
// If either 'start' or 'end' is empty or not found in the String, it returns the
436
// original String as the second String, and an empty String as the first.
437
//
438
// Parameters:
439
//
440
// - start (String): The String marking the beginning of the text to be cut.
441
//
442
// - end (String): The String marking the end of the text to be cut.
443
//
444
//   - rmtags (bool, optional): An optional boolean parameter indicating whether
445
//     to remove 'start' and 'end' tags from the cut text. Defaults to false.
446
//
447
// Returns:
448
//
449
//   - String: The first String containing the remainder of the original String
450
//     after the cut, with tags removed if specified,
451
//     or an empty String if 'start' or 'end' is empty or not found.
452
//
453
//   - String: The second String containing the text between the first occurrences of
454
//     'start' and 'end', or the original String if 'start' or 'end' is empty or not found.
455
//
456
// Example usage:
457
//
458
//        s := g.String("Hello, [world]! How are you?")
459
//        remainder, cut := s.Cut("[", "]")
460
//        // remainder: "Hello, ! How are you?"
461
//        // cut: "world"
462
func (s String) Cut(start, end String, rmtags ...bool) (String, String) {
10✔
463
        if start.Empty() || end.Empty() {
11✔
464
                return s, ""
1✔
465
        }
1✔
466

467
        startIndex := s.Index(start)
9✔
468
        if startIndex == -1 {
11✔
469
                return s, ""
2✔
470
        }
2✔
471

472
        startEnd := startIndex + start.Len()
7✔
473
        endIndex := s[startEnd:].Index(end)
7✔
474
        if endIndex == -1 {
8✔
475
                return s, ""
1✔
476
        }
1✔
477

478
        cut := s[startEnd : startEnd+endIndex]
6✔
479

6✔
480
        if len(rmtags) != 0 && !rmtags[0] {
6✔
UNCOV
481
                startEnd += end.Len()
×
UNCOV
482
                return s[:startIndex] + s[startIndex:startEnd+endIndex] + s[startEnd+endIndex:], cut
×
UNCOV
483
        }
×
484

485
        return s[:startIndex] + s[startEnd+endIndex+end.Len():], cut
6✔
486
}
487

488
// Similarity calculates the similarity between two Strings using the
489
// Levenshtein distance algorithm and returns the similarity percentage as an Float.
490
//
491
// The function compares two Strings using the Levenshtein distance,
492
// which measures the difference between two sequences by counting the number
493
// of single-character edits required to change one sequence into the other.
494
// The similarity is then calculated by normalizing the distance by the maximum
495
// length of the two input Strings.
496
//
497
// Parameters:
498
//
499
// - str (String): The String to compare with s.
500
//
501
// Returns:
502
//
503
// - Float: The similarity percentage between the two Strings as a value between 0 and 100.
504
//
505
// Example usage:
506
//
507
//        s1 := g.String("kitten")
508
//        s2 := g.String("sitting")
509
//        similarity := s1.Similarity(s2) // 57.14285714285714
510
func (s String) Similarity(str String) Float {
25✔
511
        if s.Eq(str) {
27✔
512
                return 100
2✔
513
        }
2✔
514

515
        if s.Empty() || str.Empty() {
24✔
516
                return 0
1✔
517
        }
1✔
518

519
        s1 := s.Runes()
22✔
520
        s2 := str.Runes()
22✔
521

22✔
522
        lenS1 := s.LenRunes()
22✔
523
        lenS2 := str.LenRunes()
22✔
524

22✔
525
        if lenS1 > lenS2 {
28✔
526
                s1, s2, lenS1, lenS2 = s2, s1, lenS2, lenS1
6✔
527
        }
6✔
528

529
        distance := NewSlice[Int](lenS1 + 1)
22✔
530

22✔
531
        for i, r2 := range s2 {
178✔
532
                prev := Int(i) + 1
156✔
533

156✔
534
                for j, r1 := range s1 {
1,224✔
535
                        current := distance[j]
1,068✔
536
                        if r2 != r1 {
1,981✔
537
                                current = distance[j].Add(1).Min(prev + 1).Min(distance[j+1] + 1)
913✔
538
                        }
913✔
539

540
                        distance[j], prev = prev, current
1,068✔
541
                }
542

543
                distance[lenS1] = prev
156✔
544
        }
545

546
        return Float(1).Sub(distance[lenS1].Float() / lenS1.Max(lenS2).Float()).Mul(100)
22✔
547
}
548

549
// Cmp compares two Strings and returns an cmp.Ordering indicating their relative order.
550
// The result will be cmp.Equal if s==str, cmp.Less if s < str, and cmp.Greater if s > str.
551
func (s String) Cmp(str String) cmp.Ordering { return cmp.Cmp(s, str) }
5✔
552

553
// Append appends the specified String to the current String.
554
func (s String) Append(str String) String { return s + str }
9✔
555

556
// Prepend prepends the specified String to the current String.
557
func (s String) Prepend(str String) String { return str + s }
4✔
558

559
// ContainsRune checks if the String contains the specified rune.
560
func (s String) ContainsRune(r rune) bool { return strings.ContainsRune(s.Std(), r) }
231✔
561

562
// Count returns the number of non-overlapping instances of the substring in the String.
563
func (s String) Count(substr String) Int { return Int(strings.Count(s.Std(), substr.Std())) }
3✔
564

565
// Empty checks if the String is empty.
566
func (s String) Empty() bool { return len(s) == 0 }
490✔
567

568
// Eq checks if two Strings are equal.
569
func (s String) Eq(str String) bool { return s == str }
149✔
570

571
// EqFold compares two String strings case-insensitively.
572
func (s String) EqFold(str String) bool { return strings.EqualFold(s.Std(), str.Std()) }
3✔
573

574
// Gt checks if the String is greater than the specified String.
575
func (s String) Gt(str String) bool { return s > str }
5✔
576

577
// Gte checks if the String is greater than or equal to the specified String.
578
func (s String) Gte(str String) bool { return s >= str }
5✔
579

580
// Bytes returns the String as an Bytes.
581
func (s String) Bytes() Bytes { return Bytes(s) }
283✔
582

583
// BytesUnsafe converts the String into Bytes without copying memory.
584
// Warning: the resulting Bytes shares the same underlying memory as the original String.
585
// If the original String is modified through unsafe operations (rare), or if it is garbage collected,
586
// the Bytes may become invalid or cause undefined behavior.
UNCOV
587
func (s String) BytesUnsafe() Bytes { return Bytes(*(*[]byte)(unsafe.Pointer(&s))) }
×
588

589
// Index returns the index of the first instance of the specified substring in the String, or -1
590
// if substr is not present in s.
591
func (s String) Index(substr String) Int { return Int(strings.Index(s.Std(), substr.Std())) }
739✔
592

593
// LastIndex returns the index of the last instance of the specified substring in the String, or -1
594
// if substr is not present in s.
595
func (s String) LastIndex(substr String) Int { return Int(strings.LastIndex(s.Std(), substr.Std())) }
35✔
596

597
// IndexRune returns the index of the first instance of the specified rune in the String.
598
func (s String) IndexRune(r rune) Int { return Int(strings.IndexRune(s.Std(), r)) }
3✔
599

600
// Len returns the length of the String.
601
func (s String) Len() Int { return Int(len(s)) }
526✔
602

603
// LenRunes returns the number of runes in the String.
604
func (s String) LenRunes() Int { return Int(utf8.RuneCountInString(s.Std())) }
77✔
605

606
// Lt checks if the String is less than the specified String.
607
func (s String) Lt(str String) bool { return s < str }
5✔
608

609
// Lte checks if the String is less than or equal to the specified String.
610
func (s String) Lte(str String) bool { return s <= str }
5✔
611

612
// Map applies the provided function to all runes in the String and returns the resulting String.
613
func (s String) Map(fn func(rune) rune) String { return String(strings.Map(fn, s.Std())) }
9✔
614

615
// NormalizeNFC returns a new String with its Unicode characters normalized using the NFC form.
616
func (s String) NormalizeNFC() String { return String(norm.NFC.String(s.Std())) }
13✔
617

618
// Ne checks if two Strings are not equal.
619
func (s String) Ne(str String) bool { return !s.Eq(str) }
74✔
620

621
// NotEmpty checks if the String is not empty.
622
func (s String) NotEmpty() bool { return s.Len() != 0 }
204✔
623

624
// Reader returns a *strings.Reader initialized with the content of String.
625
func (s String) Reader() *strings.Reader { return strings.NewReader(s.Std()) }
11✔
626

627
// Repeat returns a new String consisting of the specified count of the original String.
628
func (s String) Repeat(count Int) String { return String(strings.Repeat(s.Std(), count.Std())) }
7✔
629

630
// Reverse reverses the String.
631
func (s String) Reverse() String { return s.Bytes().Reverse().String() }
35✔
632

633
// Runes returns the String as a slice of runes.
634
func (s String) Runes() Slice[rune] { return []rune(s) }
363✔
635

636
// Chars splits the String into individual characters and returns the iterator.
637
func (s String) Chars() SeqSlice[String] { return s.Split() }
7✔
638

639
// SubString extracts a substring from the String starting at the 'start' index and ending before the 'end' index.
640
// The function also supports an optional 'step' parameter to define the increment between indices in the substring.
641
// If 'start' or 'end' index is negative, they represent positions relative to the end of the String:
642
// - A negative 'start' index indicates the position from the end of the String, moving backward.
643
// - A negative 'end' index indicates the position from the end of the String.
644
// The function ensures that indices are adjusted to fall within the valid range of the String's length.
645
// If indices are out of bounds or if 'start' exceeds 'end', the function returns the original String unmodified.
646
func (s String) SubString(start, end Int, step ...Int) String {
6✔
647
        return String(s.Runes().SubSlice(start, end, step...))
6✔
648
}
6✔
649

650
// Std returns the String as a string.
651
func (s String) Std() string { return string(s) }
3,873✔
652

653
// Format applies a specified format to the String object.
654
func (s String) Format(template String) String { return Format(template, s) }
8✔
655

656
// Truncate shortens the String to the specified maximum length. If the String exceeds the
657
// specified length, it is truncated, and an ellipsis ("...") is appended to indicate the truncation.
658
//
659
// If the length of the String is less than or equal to the specified maximum length, the
660
// original String is returned unchanged.
661
//
662
// The method respects Unicode characters and truncates based on the number of runes,
663
// not bytes.
664
//
665
// Parameters:
666
//   - max: The maximum number of runes allowed in the resulting String.
667
//
668
// Returns:
669
//   - A new String truncated to the specified maximum length with "..." appended
670
//     if truncation occurs. Otherwise, returns the original String.
671
//
672
// Example usage:
673
//
674
//        s := g.String("Hello, World!")
675
//        result := s.Truncate(5)
676
//        // result: "Hello..."
677
//
678
//        s2 := g.String("Short")
679
//        result2 := s2.Truncate(10)
680
//        // result2: "Short"
681
//
682
//        s3 := g.String("😊😊😊😊😊")
683
//        result3 := s3.Truncate(3)
684
//        // result3: "😊😊😊..."
685
func (s String) Truncate(max Int) String {
11✔
686
        if max.IsNegative() || s.LenRunes().Lte(max) {
17✔
687
                return s
6✔
688
        }
6✔
689

690
        return String(s.Runes().SubSlice(0, max)).Append("...")
5✔
691
}
692

693
// LeftJustify justifies the String to the left by adding padding to the right, up to the
694
// specified length. If the length of the String is already greater than or equal to the specified
695
// length, or the pad is empty, the original String is returned.
696
//
697
// The padding String is repeated as necessary to fill the remaining length.
698
// The padding is added to the right of the String.
699
//
700
// Parameters:
701
//   - length: The desired length of the resulting justified String.
702
//   - pad: The String used as padding.
703
//
704
// Example usage:
705
//
706
//        s := g.String("Hello")
707
//        result := s.LeftJustify(10, "...")
708
//        // result: "Hello....."
709
func (s String) LeftJustify(length Int, pad String) String {
4✔
710
        if s.LenRunes() >= length || pad.Eq("") {
7✔
711
                return s
3✔
712
        }
3✔
713

714
        output := NewBuilder()
1✔
715

1✔
716
        _ = output.Write(s)
1✔
717
        writePadding(output, pad, pad.LenRunes(), length-s.LenRunes())
1✔
718

1✔
719
        return output.String()
1✔
720
}
721

722
// RightJustify justifies the String to the right by adding padding to the left, up to the
723
// specified length. If the length of the String is already greater than or equal to the specified
724
// length, or the pad is empty, the original String is returned.
725
//
726
// The padding String is repeated as necessary to fill the remaining length.
727
// The padding is added to the left of the String.
728
//
729
// Parameters:
730
//   - length: The desired length of the resulting justified String.
731
//   - pad: The String used as padding.
732
//
733
// Example usage:
734
//
735
//        s := g.String("Hello")
736
//        result := s.RightJustify(10, "...")
737
//        // result: ".....Hello"
738
func (s String) RightJustify(length Int, pad String) String {
4✔
739
        if s.LenRunes() >= length || pad.Empty() {
7✔
740
                return s
3✔
741
        }
3✔
742

743
        output := NewBuilder()
1✔
744

1✔
745
        writePadding(output, pad, pad.LenRunes(), length-s.LenRunes())
1✔
746
        _ = output.Write(s)
1✔
747

1✔
748
        return output.String()
1✔
749
}
750

751
// Center justifies the String by adding padding on both sides, up to the specified length.
752
// If the length of the String is already greater than or equal to the specified length, or the
753
// pad is empty, the original String is returned.
754
//
755
// The padding String is repeated as necessary to evenly distribute the remaining length on both
756
// sides.
757
// The padding is added to the left and right of the String.
758
//
759
// Parameters:
760
//   - length: The desired length of the resulting justified String.
761
//   - pad: The String used as padding.
762
//
763
// Example usage:
764
//
765
//        s := g.String("Hello")
766
//        result := s.Center(10, "...")
767
//        // result: "..Hello..."
768
func (s String) Center(length Int, pad String) String {
4✔
769
        if s.LenRunes() >= length || pad.Empty() {
7✔
770
                return s
3✔
771
        }
3✔
772

773
        output := NewBuilder()
1✔
774

1✔
775
        remains := length - s.LenRunes()
1✔
776

1✔
777
        writePadding(output, pad, pad.LenRunes(), remains/2)
1✔
778
        _ = output.Write(s)
1✔
779
        writePadding(output, pad, pad.LenRunes(), (remains+1)/2)
1✔
780

1✔
781
        return output.String()
1✔
782
}
783

784
// writePadding writes the padding String to the output Builder to fill the remaining length.
785
// It repeats the padding String as necessary and appends any remaining runes from the padding
786
// String.
787
func writePadding(output *Builder, pad String, padlen, remains Int) {
4✔
788
        if repeats := remains / padlen; repeats > 0 {
8✔
789
                _ = output.Write(pad.Repeat(repeats))
4✔
790
        }
4✔
791

792
        padrunes := pad.Runes()
4✔
793
        for i := range remains % padlen {
4✔
UNCOV
794
                _ = output.WriteRune(padrunes[i])
×
UNCOV
795
        }
×
796
}
797

798
// Print writes the content of the String to the standard output (console)
799
// and returns the String unchanged.
UNCOV
800
func (s String) Print() String { fmt.Print(s); return s }
×
801

802
// Println writes the content of the String to the standard output (console) with a newline
803
// and returns the String unchanged.
UNCOV
804
func (s String) Println() String { fmt.Println(s); return s }
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc