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

enetx / g / 16068682304

04 Jul 2025 07:49AM UTC coverage: 85.689% (-0.07%) from 85.762%
16068682304

push

github

enetx
fix Format

6 of 7 new or added lines in 2 files covered. (85.71%)

5 existing lines in 1 file now uncovered.

3826 of 4465 relevant lines covered (85.69%)

108.47 hits per line

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

95.88
/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) }
308✔
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.
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 {
1✔
30
        b := new(Builder)
1✔
31
        b.WriteString(s)
1✔
32
        return b
1✔
33
}
1✔
34

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

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

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

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

65
        var b Builder
300✔
66

300✔
67
        for range length {
12,660✔
68
                b.WriteRune(chars.Random())
12,360✔
69
        }
12,360✔
70

71
        return b.String()
300✔
72
}
73

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

82
        return true
5✔
83
}
84

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

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

97
        return true
2✔
98
}
99

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

107
        return Ok(Int(hint))
164✔
108
}
109

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

129
        return None[*big.Int]()
2✔
130
}
131

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

139
        return Ok(Float(float))
3✔
140
}
141

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

262
        count, i := Int(0), Int(0)
15✔
263

15✔
264
        for {
35✔
265
                pos := s[i:].Index(oldS)
20✔
266
                if pos == -1 {
24✔
267
                        break
4✔
268
                }
269

270
                pos += i
16✔
271
                count++
16✔
272

16✔
273
                if count == n || (n == -1 && s[pos+oldS.Len():].Index(oldS) == -1) {
27✔
274
                        return s[:pos] + newS + s[pos+oldS.Len():]
11✔
275
                }
11✔
276

277
                i = pos + oldS.Len()
5✔
278
        }
279

280
        return s
4✔
281
}
282

283
// Contains checks if the String contains the specified substring.
284
func (s String) Contains(substr String) bool { return f.Contains(substr)(s) }
10✔
285

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

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

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

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

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

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

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

347
// Lines splits the String by lines and returns the iterator.
348
func (s String) Lines() SeqSlice[String] {
2✔
349
        return transformSeq(strings.Lines(s.Std()), NewString).Map(String.TrimEnd)
2✔
350
}
2✔
351

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

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

363
// Split splits the String by the specified separator and returns the iterator.
364
func (s String) Split(sep ...String) SeqSlice[String] {
100✔
365
        var separator String
100✔
366
        if len(sep) != 0 {
192✔
367
                separator = sep[0]
92✔
368
        }
92✔
369

370
        return transformSeq(strings.SplitSeq(s.Std(), separator.Std()), NewString)
100✔
371
}
372

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

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

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

414
        runes := []rune(s)
4✔
415
        if size.Gte(Int(len(runes))) {
6✔
416
                return func(yield func(String) bool) { yield(s) }
4✔
417
        }
418

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

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

471
        startIndex := s.Index(start)
9✔
472
        if startIndex == -1 {
11✔
473
                return s, ""
2✔
474
        }
2✔
475

476
        startEnd := startIndex + start.Len()
7✔
477
        endIndex := s[startEnd:].Index(end)
7✔
478
        if endIndex == -1 {
8✔
479
                return s, ""
1✔
480
        }
1✔
481

482
        cut := s[startEnd : startEnd+endIndex]
6✔
483

6✔
484
        if len(rmtags) != 0 && !rmtags[0] {
6✔
485
                startEnd += end.Len()
×
486
                return s[:startIndex] + s[startIndex:startEnd+endIndex] + s[startEnd+endIndex:], cut
×
487
        }
×
488

489
        return s[:startIndex] + s[startEnd+endIndex+end.Len():], cut
6✔
490
}
491

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

519
        if s.Empty() || str.Empty() {
24✔
520
                return 0
1✔
521
        }
1✔
522

523
        s1 := s.Runes()
22✔
524
        s2 := str.Runes()
22✔
525

22✔
526
        lenS1 := s.LenRunes()
22✔
527
        lenS2 := str.LenRunes()
22✔
528

22✔
529
        if lenS1 > lenS2 {
28✔
530
                s1, s2, lenS1, lenS2 = s2, s1, lenS2, lenS1
6✔
531
        }
6✔
532

533
        distance := NewSlice[Int](lenS1 + 1)
22✔
534

22✔
535
        for i, r2 := range s2 {
178✔
536
                prev := Int(i) + 1
156✔
537

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

544
                        distance[j], prev = prev, current
1,068✔
545
                }
546

547
                distance[lenS1] = prev
156✔
548
        }
549

550
        return Float(1).Sub(distance[lenS1].Float() / lenS1.Max(lenS2).Float()).Mul(100)
22✔
551
}
552

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

557
// Append appends the specified String to the current String.
558
func (s String) Append(str String) String { return s + str }
9✔
559

560
// Prepend prepends the specified String to the current String.
561
func (s String) Prepend(str String) String { return str + s }
4✔
562

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

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

569
// Empty checks if the String is empty.
570
func (s String) Empty() bool { return len(s) == 0 }
490✔
571

572
// Eq checks if two Strings are equal.
573
func (s String) Eq(str String) bool { return s == str }
149✔
574

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

578
// Gt checks if the String is greater than the specified String.
579
func (s String) Gt(str String) bool { return s > str }
5✔
580

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

584
// Bytes returns the String as an Bytes.
585
func (s String) Bytes() Bytes { return Bytes(s) }
283✔
586

587
// BytesUnsafe converts the String into Bytes without copying memory.
588
// Warning: the resulting Bytes shares the same underlying memory as the original String.
589
// If the original String is modified through unsafe operations (rare), or if it is garbage collected,
590
// the Bytes may become invalid or cause undefined behavior.
NEW
591
func (s String) BytesUnsafe() Bytes { return unsafe.Slice(unsafe.StringData(s.Std()), len(s)) }
×
592

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

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

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

604
// Len returns the length of the String.
605
func (s String) Len() Int { return Int(len(s)) }
526✔
606

607
// LenRunes returns the number of runes in the String.
608
func (s String) LenRunes() Int { return Int(utf8.RuneCountInString(s.Std())) }
77✔
609

610
// Lt checks if the String is less than the specified String.
611
func (s String) Lt(str String) bool { return s < str }
5✔
612

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

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

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

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

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

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

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

634
// Reverse reverses the String.
635
func (s String) Reverse() String { return s.Bytes().Reverse().String() }
35✔
636

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

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

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

654
// Std returns the String as a string.
655
func (s String) Std() string { return string(s) }
3,902✔
656

657
// Format applies a specified format to the String object.
658
func (s String) Format(template String) String { return Format(template, s) }
8✔
659

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

694
        return String(s.Runes().SubSlice(0, max)).Append("...")
5✔
695
}
696

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

718
        var b Builder
1✔
719

1✔
720
        _, _ = b.WriteString(s)
1✔
721
        writePadding(&b, pad, pad.LenRunes(), length-s.LenRunes())
1✔
722

1✔
723
        return b.String()
1✔
724
}
725

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

747
        var b Builder
1✔
748

1✔
749
        writePadding(&b, pad, pad.LenRunes(), length-s.LenRunes())
1✔
750
        _, _ = b.WriteString(s)
1✔
751

1✔
752
        return b.String()
1✔
753
}
754

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

777
        var b Builder
1✔
778

1✔
779
        remains := length - s.LenRunes()
1✔
780

1✔
781
        writePadding(&b, pad, pad.LenRunes(), remains/2)
1✔
782
        _, _ = b.WriteString(s)
1✔
783
        writePadding(&b, pad, pad.LenRunes(), (remains+1)/2)
1✔
784

1✔
785
        return b.String()
1✔
786
}
787

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

796
        padrunes := pad.Runes()
4✔
797
        for i := range remains % padlen {
4✔
798
                _, _ = b.WriteRune(padrunes[i])
×
799
        }
×
800
}
801

802
// Print writes the content of the String to the standard output (console)
803
// and returns the String unchanged.
804
func (s String) Print() String { fmt.Print(s); return s }
×
805

806
// Println writes the content of the String to the standard output (console) with a newline
807
// and returns the String unchanged.
808
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