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

enetx / g / 16991077829

15 Aug 2025 01:32PM UTC coverage: 88.742% (-0.2%) from 88.915%
16991077829

push

github

enetx
ref opt

283 of 305 new or added lines in 16 files covered. (92.79%)

4 existing lines in 4 files now uncovered.

4296 of 4841 relevant lines covered (88.74%)

866.46 hits per line

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

96.32
/string.go
1
package g
2

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

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

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

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

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

29
// Builder returns a new Builder initialized with the content of the String.
30
func (s String) Builder() *Builder {
1✔
31
        b := new(Builder)
1✔
32
        b.WriteString(s)
1✔
33
        return b
1✔
34
}
1✔
35

36
// Min returns the minimum of Strings.
37
func (s String) Min(b ...String) String { return cmp.Min(append(b, s)...) }
3✔
38

39
// Max returns the maximum of Strings.
40
func (s String) Max(b ...String) String { return cmp.Max(append(b, s)...) }
3✔
41

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

300✔
60
        if len(letters) != 0 {
300✔
61
                chars = letters[0].Runes()
×
62
        } else {
300✔
63
                chars = (ASCII_LETTERS + DIGITS).Runes()
300✔
64
        }
300✔
65

66
        var b Builder
300✔
67
        b.Grow(length)
300✔
68

300✔
69
        for range length {
12,806✔
70
                b.WriteRune(chars.Random())
12,506✔
71
        }
12,506✔
72

73
        return b.String()
300✔
74
}
75

76
// IsASCII checks if all characters in the String are ASCII bytes.
77
func (s String) IsASCII() bool {
8✔
78
        for _, r := range s {
72✔
79
                if r > unicode.MaxASCII {
67✔
80
                        return false
3✔
81
                }
3✔
82
        }
83

84
        return true
5✔
85
}
86

87
// IsDigit checks if all characters in the String are digits.
88
func (s String) IsDigit() bool {
4✔
89
        if s.Empty() {
5✔
90
                return false
1✔
91
        }
1✔
92

93
        for _, c := range s {
14✔
94
                if !unicode.IsDigit(c) {
12✔
95
                        return false
1✔
96
                }
1✔
97
        }
98

99
        return true
2✔
100
}
101

102
// ToInt tries to parse the String as an int and returns an Int.
103
func (s String) ToInt() Result[Int] {
243✔
104
        hint, err := strconv.ParseInt(s.Std(), 0, 64)
243✔
105
        if err != nil {
289✔
106
                return Err[Int](err)
46✔
107
        }
46✔
108

109
        return Ok(Int(hint))
197✔
110
}
111

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

131
        return None[*big.Int]()
2✔
132
}
133

134
// ToFloat tries to parse the String as a float64 and returns an Float.
135
func (s String) ToFloat() Result[Float] {
10✔
136
        float, err := strconv.ParseFloat(s.Std(), 64)
10✔
137
        if err != nil {
15✔
138
                return Err[Float](err)
5✔
139
        }
5✔
140

141
        return Ok(Float(float))
5✔
142
}
143

144
// Title converts the String to title case.
145
func (s String) Title() String { return String(title.String(s.Std())) }
29✔
146

147
// Lower returns the String in lowercase.
148
func (s String) Lower() String { return s.Bytes().Lower().String() }
7✔
149

150
// Upper returns the String in uppercase.
151
func (s String) Upper() String { return s.Bytes().Upper().String() }
8✔
152

153
// Trim removes leading and trailing white space from the String.
154
func (s String) Trim() String { return String(strings.TrimSpace(s.Std())) }
240✔
155

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

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

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

165
// TrimStartSet removes the specified set of characters from the beginning of the String.
166
func (s String) TrimStartSet(cutset String) String {
5✔
167
        return String(strings.TrimLeft(s.Std(), cutset.Std()))
5✔
168
}
5✔
169

170
// TrimEndSet removes the specified set of characters from the end of the String.
171
func (s String) TrimEndSet(cutset String) String {
5✔
172
        return String(strings.TrimRight(s.Std(), cutset.Std()))
5✔
173
}
5✔
174

175
// StripPrefix trims the specified prefix from the String.
176
func (s String) StripPrefix(prefix String) String {
4✔
177
        return String(strings.TrimPrefix(s.Std(), prefix.Std()))
4✔
178
}
4✔
179

180
// StripSuffix trims the specified suffix from the String.
181
func (s String) StripSuffix(suffix String) String {
6✔
182
        return String(strings.TrimSuffix(s.Std(), suffix.Std()))
6✔
183
}
6✔
184

185
// Replace replaces the 'oldS' String with the 'newS' String for the specified number of
186
// occurrences.
187
func (s String) Replace(oldS, newS String, n Int) String {
6✔
188
        return String(strings.Replace(s.Std(), oldS.Std(), newS.Std(), n.Std()))
6✔
189
}
6✔
190

191
// ReplaceAll replaces all occurrences of the 'oldS' String with the 'newS' String.
192
func (s String) ReplaceAll(oldS, newS String) String {
5✔
193
        return String(strings.ReplaceAll(s.Std(), oldS.Std(), newS.Std()))
5✔
194
}
5✔
195

196
// ReplaceMulti creates a custom replacer to perform multiple string replacements.
197
//
198
// Parameters:
199
//
200
// - oldnew ...String: Pairs of strings to be replaced. Specify as many pairs as needed.
201
//
202
// Returns:
203
//
204
// - String: A new string with replacements applied using the custom replacer.
205
//
206
// Example usage:
207
//
208
//        original := g.String("Hello, world! This is a test.")
209
//        replaced := original.ReplaceMulti(
210
//            "Hello", "Greetings",
211
//            "world", "universe",
212
//            "test", "example",
213
//        )
214
//        // replaced contains "Greetings, universe! This is an example."
215
func (s String) ReplaceMulti(oldnew ...String) String {
4✔
216
        pairs := make([]string, len(oldnew))
4✔
217
        for i, str := range oldnew {
20✔
218
                pairs[i] = str.Std()
16✔
219
        }
16✔
220

221
        return String(strings.NewReplacer(pairs...).Replace(s.Std()))
4✔
222
}
223

224
// Remove removes all occurrences of specified substrings from the String.
225
//
226
// Parameters:
227
//
228
// - matches ...String: Substrings to be removed from the string. Specify as many substrings as needed.
229
//
230
// Returns:
231
//
232
// - String: A new string with all specified substrings removed.
233
//
234
// Example usage:
235
//
236
//        original := g.String("Hello, world! This is a test.")
237
//        modified := original.Remove(
238
//            "Hello",
239
//            "test",
240
//        )
241
//        // modified contains ", world! This is a ."
242
func (s String) Remove(matches ...String) String {
3✔
243
        if len(matches) == 0 {
3✔
NEW
244
                return s
×
NEW
245
        }
×
246

247
        pairs := make([]string, len(matches)*2)
3✔
248
        for i, match := range matches {
9✔
249
                pairs[i*2] = match.Std()
6✔
250
                pairs[i*2+1] = ""
6✔
251
        }
6✔
252

253
        return String(strings.NewReplacer(pairs...).Replace(s.Std()))
3✔
254
}
255

256
// ReplaceNth returns a new String instance with the nth occurrence of oldS
257
// replaced with newS. If there aren't enough occurrences of oldS, the
258
// original String is returned. If n is less than -1, the original String
259
// is also returned. If n is -1, the last occurrence of oldS is replaced with newS.
260
//
261
// Returns:
262
//
263
// - A new String instance with the nth occurrence of oldS replaced with newS.
264
//
265
// Example usage:
266
//
267
//        s := g.String("The quick brown dog jumped over the lazy dog.")
268
//        result := s.ReplaceNth("dog", "fox", 2)
269
//        fmt.Println(result)
270
//
271
// Output: "The quick brown dog jumped over the lazy fox.".
272
func (s String) ReplaceNth(oldS, newS String, n Int) String {
18✔
273
        if n < -1 || len(oldS) == 0 {
21✔
274
                return s
3✔
275
        }
3✔
276

277
        count, i := Int(0), Int(0)
15✔
278

15✔
279
        for {
35✔
280
                pos := s[i:].Index(oldS)
20✔
281
                if pos == -1 {
24✔
282
                        break
4✔
283
                }
284

285
                pos += i
16✔
286
                count++
16✔
287

16✔
288
                if count == n || (n == -1 && s[pos+oldS.Len():].Index(oldS) == -1) {
27✔
289
                        return s[:pos] + newS + s[pos+oldS.Len():]
11✔
290
                }
11✔
291

292
                i = pos + oldS.Len()
5✔
293
        }
294

295
        return s
4✔
296
}
297

298
// Contains checks if the String contains the specified substring.
299
func (s String) Contains(substr String) bool { return f.Contains(substr)(s) }
11✔
300

301
// ContainsAny checks if the String contains any of the specified substrings.
302
func (s String) ContainsAny(substrs ...String) bool {
4✔
303
        return slices.ContainsFunc(substrs, s.Contains)
4✔
304
}
4✔
305

306
// ContainsAll checks if the given String contains all the specified substrings.
307
func (s String) ContainsAll(substrs ...String) bool {
4✔
308
        for _, substr := range substrs {
9✔
309
                if !s.Contains(substr) {
7✔
310
                        return false
2✔
311
                }
2✔
312
        }
313

314
        return true
2✔
315
}
316

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

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

324
// StartsWithAny checks if the String starts with any of the provided prefixes.
325
// The method accepts a variable number of arguments, allowing for checking against multiple
326
// prefixes at once. It iterates over the provided prefixes and uses the HasPrefix function from
327
// the strings package to check if the String starts with each prefix.
328
// The function returns true if the String starts with any of the prefixes, and false otherwise.
329
//
330
// Example usage:
331
//
332
//        s := g.String("http://example.com")
333
//        if s.StartsWithAny("http://", "https://") {
334
//           // do something
335
//        }
336
func (s String) StartsWithAny(prefixes ...String) bool {
5✔
337
        return slices.ContainsFunc(prefixes, s.StartsWith)
5✔
338
}
5✔
339

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

344
// EndsWithAny checks if the String ends with any of the provided suffixes.
345
// The method accepts a variable number of arguments, allowing for checking against multiple
346
// suffixes at once. It iterates over the provided suffixes and uses the HasSuffix function from
347
// the strings package to check if the String ends with each suffix.
348
// The function returns true if the String ends with any of the suffixes, and false otherwise.
349
//
350
// Example usage:
351
//
352
//        s := g.String("example.com")
353
//        if s.EndsWithAny(".com", ".net") {
354
//           // do something
355
//        }
356
func (s String) EndsWithAny(suffixes ...String) bool {
3✔
357
        return slices.ContainsFunc(suffixes, s.EndsWith)
3✔
358
}
3✔
359

360
// Lines splits the String by lines and returns the iterator.
361
func (s String) Lines() SeqSlice[String] {
2✔
362
        return transformSeq(strings.Lines(s.Std()), NewString).Map(String.TrimEnd)
2✔
363
}
2✔
364

365
// Fields splits the String into a slice of substrings, removing any whitespace, and returns the iterator.
366
func (s String) Fields() SeqSlice[String] {
4✔
367
        return transformSeq(strings.FieldsSeq(s.Std()), NewString)
4✔
368
}
4✔
369

370
// FieldsBy splits the String into a slice of substrings using a custom function to determine the field boundaries,
371
// and returns the iterator.
372
func (s String) FieldsBy(fn func(r rune) bool) SeqSlice[String] {
3✔
373
        return transformSeq(strings.FieldsFuncSeq(s.Std(), fn), NewString)
3✔
374
}
3✔
375

376
// Split splits the String by the specified separator and returns the iterator.
377
func (s String) Split(sep ...String) SeqSlice[String] {
108✔
378
        var separator String
108✔
379
        if len(sep) != 0 {
208✔
380
                separator = sep[0]
100✔
381
        }
100✔
382

383
        return transformSeq(strings.SplitSeq(s.Std(), separator.Std()), NewString)
108✔
384
}
385

386
// SplitAfter splits the String after each instance of the specified separator and returns the iterator.
387
func (s String) SplitAfter(sep String) SeqSlice[String] {
8✔
388
        return transformSeq(strings.SplitAfterSeq(s.Std(), sep.Std()), NewString)
8✔
389
}
8✔
390

391
// SplitN splits the String into substrings using the provided separator and returns an Slice[String] of the results.
392
// The n parameter controls the number of substrings to return:
393
// - If n is negative, there is no limit on the number of substrings returned.
394
// - If n is zero, an empty Slice[String] is returned.
395
// - If n is positive, at most n substrings are returned.
396
func (s String) SplitN(sep String, n Int) Slice[String] {
3✔
397
        return TransformSlice(strings.SplitN(s.Std(), sep.Std(), n.Std()), NewString)
3✔
398
}
3✔
399

400
// Chunks splits the String into chunks of the specified size.
401
//
402
// This function iterates through the String, creating new String chunks of the specified size.
403
// If size is less than or equal to 0 or the String is empty,
404
// it returns an empty Slice[String].
405
// If size is greater than or equal to the length of the String,
406
// it returns an Slice[String] containing the original String.
407
//
408
// Parameters:
409
//
410
// - size (Int): The size of the chunks to split the String into.
411
//
412
// Returns:
413
//
414
// - Slice[String]: A slice of String chunks of the specified size.
415
//
416
// Example usage:
417
//
418
//        text := g.String("Hello, World!")
419
//        chunks := text.Chunks(4)
420
//
421
// chunks contains {"Hell", "o, W", "orld", "!"}.
422
func (s String) Chunks(size Int) SeqSlice[String] {
6✔
423
        if size.Lte(0) || s.Empty() {
8✔
424
                return func(func(String) bool) {}
4✔
425
        }
426

427
        runes := s.Runes()
4✔
428
        if size.Gte(Int(len(runes))) {
6✔
429
                return func(yield func(String) bool) { yield(s) }
4✔
430
        }
431

432
        n := size.Std()
2✔
433
        return func(yield func(String) bool) {
4✔
434
                for i := 0; i < len(runes); i += n {
9✔
435
                        end := min(i+n, len(runes))
7✔
436
                        if !yield(String(runes[i:end])) {
7✔
437
                                return
×
438
                        }
×
439
                }
440
        }
441
}
442

443
// Cut returns two String values. The first String contains the remainder of the
444
// original String after the cut. The second String contains the text between the
445
// first occurrences of the 'start' and 'end' strings, with tags removed if specified.
446
//
447
// The function searches for the 'start' and 'end' strings within the String.
448
// If both are found, it returns the first String containing the remainder of the
449
// original String after the cut, followed by the second String containing the text
450
// between the first occurrences of 'start' and 'end' with tags removed if specified.
451
//
452
// If either 'start' or 'end' is empty or not found in the String, it returns the
453
// original String as the second String, and an empty String as the first.
454
//
455
// Parameters:
456
//
457
// - start (String): The String marking the beginning of the text to be cut.
458
//
459
// - end (String): The String marking the end of the text to be cut.
460
//
461
//   - rmtags (bool, optional): An optional boolean parameter indicating whether
462
//     to remove 'start' and 'end' tags from the cut text. Defaults to false.
463
//
464
// Returns:
465
//
466
//   - String: The first String containing the remainder of the original String
467
//     after the cut, with tags removed if specified,
468
//     or an empty String if 'start' or 'end' is empty or not found.
469
//
470
//   - String: The second String containing the text between the first occurrences of
471
//     'start' and 'end', or the original String if 'start' or 'end' is empty or not found.
472
//
473
// Example usage:
474
//
475
//        s := g.String("Hello, [world]! How are you?")
476
//        remainder, cut := s.Cut("[", "]")
477
//        // remainder: "Hello, ! How are you?"
478
//        // cut: "world"
479
func (s String) Cut(start, end String, rmtags ...bool) (String, String) {
10✔
480
        if start.Empty() || end.Empty() {
11✔
481
                return s, ""
1✔
482
        }
1✔
483

484
        startIndex := s.Index(start)
9✔
485
        if startIndex == -1 {
11✔
486
                return s, ""
2✔
487
        }
2✔
488

489
        startEnd := startIndex + start.Len()
7✔
490
        endIndex := s[startEnd:].Index(end)
7✔
491
        if endIndex == -1 {
8✔
492
                return s, ""
1✔
493
        }
1✔
494

495
        cut := s[startEnd : startEnd+endIndex]
6✔
496

6✔
497
        if len(rmtags) != 0 && !rmtags[0] {
6✔
498
                startEnd += end.Len()
×
499
                return s[:startIndex] + s[startIndex:startEnd+endIndex] + s[startEnd+endIndex:], cut
×
500
        }
×
501

502
        return s[:startIndex] + s[startEnd+endIndex+end.Len():], cut
6✔
503
}
504

505
// Similarity calculates the similarity between two Strings using the
506
// Levenshtein distance algorithm and returns the similarity percentage as an Float.
507
//
508
// The function compares two Strings using the Levenshtein distance,
509
// which measures the difference between two sequences by counting the number
510
// of single-character edits required to change one sequence into the other.
511
// The similarity is then calculated by normalizing the distance by the maximum
512
// length of the two input Strings.
513
//
514
// Parameters:
515
//
516
// - str (String): The String to compare with s.
517
//
518
// Returns:
519
//
520
// - Float: The similarity percentage between the two Strings as a value between 0 and 100.
521
//
522
// Example usage:
523
//
524
//        s1 := g.String("kitten")
525
//        s2 := g.String("sitting")
526
//        similarity := s1.Similarity(s2) // 57.14285714285714
527
func (s String) Similarity(str String) Float {
25✔
528
        if s.Eq(str) {
27✔
529
                return 100
2✔
530
        }
2✔
531

532
        if s.Empty() || str.Empty() {
24✔
533
                return 0
1✔
534
        }
1✔
535

536
        s1 := s.Runes()
22✔
537
        s2 := str.Runes()
22✔
538

22✔
539
        lenS1 := s.LenRunes()
22✔
540
        lenS2 := str.LenRunes()
22✔
541

22✔
542
        if lenS1 > lenS2 {
28✔
543
                s1, s2, lenS1, lenS2 = s2, s1, lenS2, lenS1
6✔
544
        }
6✔
545

546
        distance := NewSlice[Int](lenS1 + 1)
22✔
547

22✔
548
        for i, r2 := range s2 {
178✔
549
                prev := Int(i) + 1
156✔
550

156✔
551
                for j, r1 := range s1 {
1,224✔
552
                        current := distance[j]
1,068✔
553
                        if r2 != r1 {
1,981✔
554
                                current = distance[j].Add(1).Min(prev + 1).Min(distance[j+1] + 1)
913✔
555
                        }
913✔
556

557
                        distance[j], prev = prev, current
1,068✔
558
                }
559

560
                distance[lenS1] = prev
156✔
561
        }
562

563
        return Float(1).Sub(distance[lenS1].Float() / lenS1.Max(lenS2).Float()).Mul(100)
22✔
564
}
565

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

570
// Append appends the specified String to the current String.
571
func (s String) Append(str String) String { return s + str }
12✔
572

573
// Prepend prepends the specified String to the current String.
574
func (s String) Prepend(str String) String { return str + s }
4✔
575

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

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

582
// Empty checks if the String is empty.
583
func (s String) Empty() bool { return len(s) == 0 }
523✔
584

585
// Eq checks if two Strings are equal.
586
func (s String) Eq(str String) bool { return s == str }
163✔
587

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

591
// Gt checks if the String is greater than the specified String.
592
func (s String) Gt(str String) bool { return s > str }
5✔
593

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

597
// Bytes returns the String as an Bytes.
598
func (s String) Bytes() Bytes { return Bytes(s) }
276✔
599

600
// BytesUnsafe converts the String into Bytes without copying memory.
601
// Warning: the resulting Bytes shares the same underlying memory as the original String.
602
// If the original String is modified through unsafe operations (rare), or if it is garbage collected,
603
// the Bytes may become invalid or cause undefined behavior.
604
func (s String) BytesUnsafe() Bytes { return unsafe.Slice(unsafe.StringData(s.Std()), len(s)) }
1✔
605

606
// Index returns the index of the first instance of the specified substring in the String, or -1
607
// if substr is not present in s.
608
func (s String) Index(substr String) Int { return Int(strings.Index(s.Std(), substr.Std())) }
839✔
609

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

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

617
// Len returns the length of the String.
618
func (s String) Len() Int { return Int(len(s)) }
583✔
619

620
// LenRunes returns the number of runes in the String.
621
func (s String) LenRunes() Int { return Int(utf8.RuneCountInString(s.Std())) }
77✔
622

623
// Lt checks if the String is less than the specified String.
624
func (s String) Lt(str String) bool { return s < str }
5✔
625

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

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

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

635
// Ne checks if two Strings are not equal.
636
func (s String) Ne(str String) bool { return !s.Eq(str) }
80✔
637

638
// NotEmpty checks if the String is not empty.
639
func (s String) NotEmpty() bool { return s.Len() != 0 }
235✔
640

641
// Reader returns a *strings.Reader initialized with the content of String.
642
func (s String) Reader() *strings.Reader { return strings.NewReader(s.Std()) }
25✔
643

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

647
// Reverse reverses the String.
648
func (s String) Reverse() String { return s.Bytes().Reverse().String() }
35✔
649

650
// Runes returns the String as a slice of runes.
651
func (s String) Runes() Slice[rune] { return []rune(s) }
367✔
652

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

656
// SubString extracts a substring from the String starting at the 'start' index and ending before the 'end' index.
657
// The function also supports an optional 'step' parameter to define the increment between indices in the substring.
658
// If 'start' or 'end' index is negative, they represent positions relative to the end of the String:
659
// - A negative 'start' index indicates the position from the end of the String, moving backward.
660
// - A negative 'end' index indicates the position from the end of the String.
661
// The function ensures that indices are adjusted to fall within the valid range of the String's length.
662
// If indices are out of bounds or if 'start' exceeds 'end', the function returns the original String unmodified.
663
func (s String) SubString(start, end Int, step ...Int) String {
6✔
664
        return String(s.Runes().SubSlice(start, end, step...))
6✔
665
}
6✔
666

667
// Std returns the String as a string.
668
func (s String) Std() string { return string(s) }
4,829✔
669

670
// Format applies a specified format to the String object.
UNCOV
671
func (s String) Format(template String) String { return Format(template, s) }
×
672

673
// Truncate shortens the String to the specified maximum length. If the String exceeds the
674
// specified length, it is truncated, and an ellipsis ("...") is appended to indicate the truncation.
675
//
676
// If the length of the String is less than or equal to the specified maximum length, the
677
// original String is returned unchanged.
678
//
679
// The method respects Unicode characters and truncates based on the number of runes,
680
// not bytes.
681
//
682
// Parameters:
683
//   - max: The maximum number of runes allowed in the resulting String.
684
//
685
// Returns:
686
//   - A new String truncated to the specified maximum length with "..." appended
687
//     if truncation occurs. Otherwise, returns the original String.
688
//
689
// Example usage:
690
//
691
//        s := g.String("Hello, World!")
692
//        result := s.Truncate(5)
693
//        // result: "Hello..."
694
//
695
//        s2 := g.String("Short")
696
//        result2 := s2.Truncate(10)
697
//        // result2: "Short"
698
//
699
//        s3 := g.String("😊😊😊😊😊")
700
//        result3 := s3.Truncate(3)
701
//        // result3: "😊😊😊..."
702
func (s String) Truncate(max Int) String {
11✔
703
        if max.IsNegative() || s.LenRunes().Lte(max) {
17✔
704
                return s
6✔
705
        }
6✔
706

707
        return String(s.Runes().SubSlice(0, max)).Append("...")
5✔
708
}
709

710
// LeftJustify justifies the String to the left by adding padding to the right, up to the
711
// specified length. If the length of the String is already greater than or equal to the specified
712
// length, or the pad is empty, the original String is returned.
713
//
714
// The padding String is repeated as necessary to fill the remaining length.
715
// The padding is added to the right of the String.
716
//
717
// Parameters:
718
//   - length: The desired length of the resulting justified String.
719
//   - pad: The String used as padding.
720
//
721
// Example usage:
722
//
723
//        s := g.String("Hello")
724
//        result := s.LeftJustify(10, "...")
725
//        // result: "Hello....."
726
func (s String) LeftJustify(length Int, pad String) String {
4✔
727
        if s.LenRunes() >= length || pad.Eq("") {
7✔
728
                return s
3✔
729
        }
3✔
730

731
        var b Builder
1✔
732

1✔
733
        _, _ = b.WriteString(s)
1✔
734
        writePadding(&b, pad, pad.LenRunes(), length-s.LenRunes())
1✔
735

1✔
736
        return b.String()
1✔
737
}
738

739
// RightJustify justifies the String to the right by adding padding to the left, up to the
740
// specified length. If the length of the String is already greater than or equal to the specified
741
// length, or the pad is empty, the original String is returned.
742
//
743
// The padding String is repeated as necessary to fill the remaining length.
744
// The padding is added to the left of the String.
745
//
746
// Parameters:
747
//   - length: The desired length of the resulting justified String.
748
//   - pad: The String used as padding.
749
//
750
// Example usage:
751
//
752
//        s := g.String("Hello")
753
//        result := s.RightJustify(10, "...")
754
//        // result: ".....Hello"
755
func (s String) RightJustify(length Int, pad String) String {
4✔
756
        if s.LenRunes() >= length || pad.Empty() {
7✔
757
                return s
3✔
758
        }
3✔
759

760
        var b Builder
1✔
761

1✔
762
        writePadding(&b, pad, pad.LenRunes(), length-s.LenRunes())
1✔
763
        _, _ = b.WriteString(s)
1✔
764

1✔
765
        return b.String()
1✔
766
}
767

768
// Center justifies the String by adding padding on both sides, up to the specified length.
769
// If the length of the String is already greater than or equal to the specified length, or the
770
// pad is empty, the original String is returned.
771
//
772
// The padding String is repeated as necessary to evenly distribute the remaining length on both
773
// sides.
774
// The padding is added to the left and right of the String.
775
//
776
// Parameters:
777
//   - length: The desired length of the resulting justified String.
778
//   - pad: The String used as padding.
779
//
780
// Example usage:
781
//
782
//        s := g.String("Hello")
783
//        result := s.Center(10, "...")
784
//        // result: "..Hello..."
785
func (s String) Center(length Int, pad String) String {
4✔
786
        if s.LenRunes() >= length || pad.Empty() {
7✔
787
                return s
3✔
788
        }
3✔
789

790
        var b Builder
1✔
791

1✔
792
        remains := length - s.LenRunes()
1✔
793

1✔
794
        writePadding(&b, pad, pad.LenRunes(), remains/2)
1✔
795
        _, _ = b.WriteString(s)
1✔
796
        writePadding(&b, pad, pad.LenRunes(), (remains+1)/2)
1✔
797

1✔
798
        return b.String()
1✔
799
}
800

801
// writePadding writes the padding String to the output Builder to fill the remaining length.
802
// It repeats the padding String as necessary and appends any remaining runes from the padding
803
// String.
804
func writePadding(b *Builder, pad String, padlen, remains Int) {
4✔
805
        if repeats := remains / padlen; repeats > 0 {
8✔
806
                _, _ = b.WriteString(pad.Repeat(repeats))
4✔
807
        }
4✔
808

809
        padrunes := pad.Runes()
4✔
810
        for i := range remains % padlen {
4✔
811
                _, _ = b.WriteRune(padrunes[i])
×
812
        }
×
813
}
814

815
// Print writes the content of the String to the standard output (console)
816
// and returns the String unchanged.
817
func (s String) Print() String { fmt.Print(s); return s }
1✔
818

819
// Println writes the content of the String to the standard output (console) with a newline
820
// and returns the String unchanged.
821
func (s String) Println() String { fmt.Println(s); return s }
1✔
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